82. Remove Duplicates from Sorted List II

  • Total Accepted: 97678
  • Total Submissions: 339601
  • Difficulty: Medium
  • Contributors: Admin

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

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

分析


使用三个指针
pre, cur, sub
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
45
/**
 * 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 || head->next == NULL) return head;
         
        ListNode dummy(0);
        ListNode* pre = &dummy;
        ListNode* cur = head;
        dummy.next = head;
        while(cur != NULL && cur->next != NULL){
            //sub record the first node tha differ with cur
            ListNode* sub = cur->next;
            while(sub != NULL && cur->val == sub->val){
                sub = sub->next;
            }
             
            if(cur->next != sub){
                pre->next = sub;
                deleteList(cur, sub);
                cur = sub;
            }
            else{
                pre = cur;
                cur = cur->next;
            }
        }
        return dummy.next;
    }
     
    void deleteList(ListNode* head, ListNode* end){
        while(head != end){
            ListNode* d = head;
            head = head->next;
            delete d;
        }
    }
};

使用递归方法
找到最接近的unique的node,对之后的进行delete
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head == NULL || head->next == NULL) return head;
         
        ListNode* p = head->next;
        if(head->val != p->val){
            head->next = deleteDuplicates(p);
            return head;
        }
        else{
            while(p != NULL && p->val == head->val) p = p->next;
            return deleteDuplicates(p);
        }
         
    }
};




posted @ 2017-02-15 20:53  copperface  阅读(208)  评论(0编辑  收藏  举报