82. Remove Duplicates from Sorted List II

Problem:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

Solutions:

/**
 * 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) {
        ListNode* dummyHead = new ListNode(0);
        ListNode* tail = dummyHead;
        ListNode* cur = head;

        while (cur) {
            if (cur->next && cur->val == cur->next->val) {
                int val = cur->val;
                cur = cur->next->next;
                while (cur && cur->val == val) {
                    cur = cur->next;
                }
            } else {
                tail->next = cur;
                tail = cur;
                cur = cur->next;
            }
        }

        tail->next = NULL;

        return dummyHead->next;

    }
};

results matching ""

    No results matching ""