Reputation: 526
For a sorted linked list, say 1->1->1->1->2->2->3->3->4->4->4
, I want to remove all the duplicates resulting in the linked list to have every node with a unique value (i.e. the above linked list should become 1->2->3->4->
.)
ListNode* deleteDuplicates(ListNode* A)
{
ListNode *ptr = A, *nextt;
if (A == NULL)
return A;
if (A->next == NULL)
return A;
while (1)
{
if ((ptr == NULL) || (ptr->next == NULL))
break;
nextt = ptr->next;
while ((ptr->val == nextt->val) && (nextt != NULL))
nextt = nextt->next;
ptr->next = nextt;
ptr = ptr->next;
}
return A;
}
My algorithm is:
ptr
is initially pointed to the head of the linked list. Another Pointer 'nextt
points to the next node from the head. (ptr->next
).nextt
remains the same as ptr
, the nextt
pointer is traversed forward until the value is different or nextt
reaches the end of the list.However, on running the code, I receive a segmentation fault.
When we reach the end of the list, the inner while loop causes nextt
to
become NULL
. Is this the place where the error is?
Simulating a different input on paper doesn't help either. I'm not sure where the error is.
Thank you.
Upvotes: 1
Views: 154
Reputation: 295
The problem is that your condition
while((ptr->val==nextt->val) && (nextt!=NULL))
dereferences nextt
in order to access nextt->val
. When nextt
is NULL, This is an access violation.
Change your loop condition to:
while ((next != NULL) && (ptr->val == nextt->val))
so that if next == NULL
, then the condition will short-circuit and evaluate to false.
Upvotes: 4