您的位置:首页 > 其它

[leetcode] Remove Duplicates from Sorted List II

2013-04-03 15:39 211 查看
Remove Duplicates from Sorted List IIApr
22 '12

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
.

与Remove Duplicates from Sorted List的区别在于需要将所有有重复的节点删掉,考虑可以用一个set保存重复的值,注意指针不要出界。

class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
set<int> s;
ListNode *cur=head;
if(!head) return cur;
while(cur)
{
if(cur->next && cur->next->val==cur->val)
{
ListNode *temp=cur->next;
cur->next=cur->next->next;
s.insert(cur->val);
delete temp;
}
else cur=cur->next;
}
ListNode *newhead=new ListNode(0);
cur=newhead;
cur->next=head;
while(!s.empty())
{
if(cur->next->val==*(s.begin()))
{
s.erase(s.begin());
cur->next=cur->next->next;
}
else cur=cur->next;
}
head=newhead->next;
delete newhead;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: