[Leetcode] 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.

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

用一个值val来标记当前要删除的元素,如果结点的值等于val,就删除掉。如果当前值与下一个结点的值相等,就将val设成当前值。

 1 /**
 2  * Definition of ListNode
 3  * class ListNode {
 4  * public:
 5  *     int val;
 6  *     ListNode *next;
 7  *     ListNode(int val) {
 8  *         this->val = val;
 9  *         this->next = NULL;
10  *     }
11  * }
12  */
13 class Solution{
14 public:
15     /**
16      * @param head: The first node of linked list.
17      * @return: head node
18      */
19     ListNode * deleteDuplicates(ListNode *head) {
20         // write your code here
21         if (head == NULL) return NULL;
22         ListNode dummy(0);
23         ListNode *cur = head, *pre = &dummy, *tmp;
24         int val = head->val - 1;
25         while (cur != NULL) {
26             if (cur->val == val || (cur->next != NULL && cur->val == cur->next->val)) {
27                 val = cur->val;
28                 tmp = cur->next;
29                 delete cur;
30                 cur = tmp;
31             } else {
32                 pre->next = cur;
33                 cur = cur->next;
34                 pre = pre->next;
35             }
36         }
37         pre->next = NULL;
38         return dummy.next;
39     }
40 };

 

posted @ 2014-04-10 14:48  Eason Liu  阅读(148)  评论(0编辑  收藏  举报