您的位置:首页 > 其它

Remove Duplicates from Sorted List II

2015-02-26 14:26 204 查看
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 需要一个dummy header来让头处理变得简单

2 维护两个指针,一个为当前指针,一个为重复指针:如果重复指针不为当前指针的后一个,那么删掉从当前往后包括重复指针的所有元素。否则向前挪动当前指针。。。

3. 注意的是无论上一题还是这一题在处理重复指针的时候都是用的p->next=p2->next。 这个地方错了两回了。。。sigh...!!!

/**
* 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) {
ListNode* p=new ListNode(INT_MIN);
p->next=head;
head=p;
while(p->next){
ListNode* p2=p->next;
while(p2->next && p2->val==p2->next->val)
p2=p2->next;
if (p->next!=p2){
ListNode* tmp=p->next;
p->next=p2->next;
deleteDup(tmp,p2->next);
} else {
p=p->next;
}
}
ListNode *new_head=head->next;
delete head;
return new_head;
}
void deleteDup(ListNode* beg, ListNode* end){
ListNode* cur=beg;
while(cur!=end){
ListNode* tmp=cur;
cur=cur->next;
delete tmp;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode