Description

Remove Duplicates from Sorted List II

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

删除链表中有重复的结点

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
 * 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;
        }

        auto h = ListNode(0);
        h.next = head;

        auto *p1 = &h;
        auto *p2 = p1->next;
        auto *cur = p2->next;

        while (cur) {
            if (cur->val == p2->val) {
                // 循环移除重复的结点
                do {
                    cur = cur->next;
                }while(cur && cur->val == p2->val);

                p1->next = cur;  // 然后移除p2指向的结点(p1->next == p2)
                if (!cur) {
                    break;
                }
            } else {
                p1 = p2; // (p1 = p1->next)
            }

            p2 = cur;
            cur = cur->next;
        }

        return h.next;
    }
};