Leetcode 82 Solution

This article provides solution to leetcode question 82 (remove-duplicates-from-sorted-list-ii)

https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == NULL)
            return NULL;

        ListNode* prev = NULL;
        ListNode* curr = head;
        ListNode* new_head = head;

        while (curr)
        {
            if (curr->next == NULL)
                break;

            if (curr->val == curr->next->val)
            {
                ListNode* next = curr->next;

                while (next && next->val == curr->val)
                    next = next->next;

                if (prev)
                {
                    prev->next = next;
                    curr = prev->next;
                }
                else
                {
                    new_head = next;
                    curr = new_head;
                }
            }
            else
            {
                prev = curr;
                curr = curr->next;
            }
        }

        return new_head;
    }
};