您的位置:首页 > 其它

[LeetCode] Remove Duplicate from Sorted Linkded List II

2013-10-30 09:31 260 查看
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


/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head==NULL)
return head;

ListNode *p1=NULL;
ListNode *p2=head;

while(p2!=NULL)
{
if(p2->next==NULL || (p2->next!=NULL && p2->val!=p2->next->val) )
{
if(p1==NULL)
{
p1=new ListNode(0);
p1=p2;
head=p1;
}
else{
p1->next=p2;
p1=p2;
}

p2=p2->next;
//if(p2!=NULL && p2->next!=NULL)
//  p1->next=NULL;

continue;
}

int dup=p2->val;
while(p2!=NULL && p2->val==dup)
{
if(p1!=NULL)
p1->next=NULL;
ListNode *tmp=p2;
p2=p2->next;
delete tmp;
}
}

if(p1==NULL) return NULL;

return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: