I want to delete all duplicates from a linked list. I know there is an exact program on GeeksForGeeks which is very similar to mine and I could use that, but I want to understand why mine is not working.
Code:
class Node {
public:
int data;
Node *next;
};
void removeDuplicatesAlpha(Node* start)
{
Node* ptr1 = start;
Node* ptr2 = NULL;
Node* dup = NULL;
int i = 0;
/* Pick elements one by one */
while (ptr1 != NULL && ptr1->next != NULL)
{
ptr2 = ptr1->next;
//0 1 2 3 4
/* Compare the picked element with rest
of the elements */
while (ptr2 != NULL && ptr2->next != NULL)
{
cout << i;
i++;
/* If duplicate then delete it */
if (ptr1->data == ptr2->data)
{
/* sequence of steps is important here */
dup = ptr2;
ptr2 = ptr2->next;
delete(dup);
}
else /* This is tricky */
ptr2 = ptr2->next;
}
ptr1 = ptr1->next;
}
}
int main()
{
Node* head = NULL;
push(&head, 3);
push(&head, 3);
push(&head, 20);
push(&head, 14);
push(&head, 9);
push(&head, 20);
push(&head, 20);
printList(head);
//removeDuplicates(head);
removeDuplicatesAlpha(head);
printList(head);
deleteList(&head);
return 0;
}
The last i printed is 4.
This is the error: Exception thrown: read access violation. ptr2 was 0xDDDDDDDD.
I'm so sorry if this is a dumb question but I just started working with Data Structures in C++.