Leetcode 83 Solution

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

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

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;

        while (curr)
        {
            if (prev == NULL)
            {
                prev = curr;
                curr = curr->next;
            }
            else
            {
                if (prev->val == curr->val)
                {
                    prev->next = curr->next;
                    curr = curr->next;
                }
                else
                {
                    prev = curr;
                    curr = curr->next;
                }
            }
        }

        return head;
    }
};