LeetCode Remove Duplicates from Sorted List II

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        if (head == NULL || head->next == NULL) return head;
        
        ListNode *tail = NULL, *h = NULL, *cur = head->next;
        ListNode *prev = head;
        
        bool nodup = true;

        while (cur != NULL) {
            if (cur->val != prev->val) {
                if (nodup) {
                    if (h == NULL) {
                        h=tail=prev;
                    } else {
                        tail->next = prev;
                        tail = prev;
                    }
                    tail->next = NULL;
                } else {
                    nodup = true;   // reset the flag
                }
            } else {
                nodup = false;
            }
            prev = cur;
            cur = cur->next;
        }

        if (nodup) {
            if (h == NULL) {
                h = prev;
            } else {
                tail->next = prev;
            }
        }
        return h;
    }
};

需要仔细写啊

第二轮:

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.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9  // 9:40
10 class Solution {
11 public:
12     ListNode *deleteDuplicates(ListNode *head) {
13         if (head == NULL) {
14             return NULL;
15         }
16         ListNode fakeHead(0);
17         ListNode* last = &fakeHead;
18         ListNode* cur = head->next;
19         ListNode* pre = head;
20         int cnt = 1;
21         while (cur != NULL) {
22             if (cur->val != pre->val) {
23                 if (cnt == 1) {
24                     last->next = pre;
25                     last = pre;
26                 }
27                 cnt = 1;
28             } else {
29                 cnt++;
30             }
31             pre = cur;
32             cur = cur->next;
33         }
34         
35         if (cnt == 1) {
36             last->next = pre;
37             last = pre;
38         }
39         last->next = NULL;
40         
41         return fakeHead.next;
42     }
43 };

 

posted @ 2014-04-17 20:23  卖程序的小歪  阅读(116)  评论(0编辑  收藏  举报