您的位置:首页 > 其它

Remove Duplicates from Sorted List I,II

2015-09-09 12:39 253 查看



Remove Duplicates from Sorted List

 

Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,

Given 
1->1->2
, return 
1->2
.

Given 
1->1->2->3->3
, return 
1->2->3
.

Hide Tags
 Linked List

<span style="font-weight: normal;">    ListNode* deleteDuplicates(ListNode* head) {
if(head==NULL || head->next==NULL)
return head;
ListNode* pp=head;
ListNode* p=head->next;

while(p){
if(p->val != pp->val){
pp = pp->next;
p = p->next;
}else{
pp->next = p->next;
p = p->next;
}
}
return head;
}</span>




Question

 Solution 


Remove Duplicates from Sorted List 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
.

Hide Tags
 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 || head->next==NULL)
return head;

ListNode* pp=new ListNode(-1);
pp->next=head;
ListNode* p=head;
ListNode* cur=pp;

while(p){
bool isDuplicates=false;
while(p->next != NULL && p->val == p->next->val){
isDuplicates=true;
p=p->next;
}
if(isDuplicates){
p=p->next;
continue;//eg.[1,1]
}
cur->next=p;
cur=cur->next;
p=p->next;
}
cur->next=p;
return pp->next;
}
};

void main(){
ListNode *head = new ListNode(1);
ListNode *l1 = new ListNode(1);
ListNode *l2 = new ListNode(1);
ListNode *l3 = new ListNode(2);
ListNode *l4 = new ListNode(3);

head->next = l1;
l1->next = l2;
l2->next = l3;
l3->next = l4;
l4->next = NULL;

Solution s;
s.deleteDuplicates(head);
}


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