您的位置:首页 > 其它

【Leetcode长征系列】Remove Duplicates from Sorted List II

2014-08-03 19:52 357 查看
原题:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct 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
.

代码:

/**
* 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;
if(head->next==NULL) return head;
ListNode *tmp = head, *pre;

pre = NULL;
while(tmp){
if (tmp->val==tmp->next->val) {
ListNode *s = tmp->next;
while (s->next!=NULL && s->val==s->next->val){
s = s->next;
}
if(pre==NULL){
if(s->next!=NULL){
head = s->next;
tmp = head;
}
else return NULL;
}
else{
pre->next = s->next;
tmp = pre->next;
}
}
else {
pre = tmp;
tmp = tmp->next;
}

if (tmp==NULL || tmp->next==NULL) break;
}
return head;
}
};

需要注意的特殊情况:

1. {1}

2. {1->2}

3. {1->1->2}

要注意pre的初始值!NULL最佳,本次情况下不适合用head作为初始值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: