LeetCode OJ:Remove Duplicates from Sorted List II(链表去重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.

这里对于链表去重是要将有重复的链表节点全部都去掉,一个都不能留,思路还是比较简单的,跟前面的I那一题实际上差不多,代码如下所示:

 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 class Solution {
10 public:
11     ListNode* deleteDuplicates(ListNode* head) {
12         if(!head) return NULL;
13         ListNode * helper = new ListNode(INT_MAX);
14         helper->next = head;
15         ListNode * prev = helper;
16         ListNode * curr = head;
17         while(curr){
18             if(curr->next && curr->val == curr->next->val){
19                 ListNode * tmpNode = curr->next;
20                 while(tmpNode->next && curr->val == tmpNode->next->val){
21                     tmpNode = tmpNode->next;
22                 }
23                 prev->next = tmpNode->next;
24                 curr = prev->next;
25             }else{
26                 prev = curr;
27                 curr = curr->next;
28             }
29         }
30         return helper->next;
31     }
32 };

 

posted @ 2016-01-14 21:24  eversliver  阅读(284)  评论(0编辑  收藏  举报