deathstroke
deathstroke

Reputation: 526

C++ Linked List gives Segmentation fault when removing nodes with duplicate values

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:

  1. A pointer ptr is initially pointed to the head of the linked list. Another Pointer 'nextt points to the next node from the head. (ptr->next).
  2. While the value of 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

Answers (1)

limits
limits

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

Related Questions