您的位置:首页 > 其它

Remove Duplicates from Sorted List I II

2014-08-25 20:08 204 查看


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
.

题意:删除给定的链表中多次出现的节点,仅保留一次。

分析:遍历一遍,如果cur节点的下一个点值与cur相同,直接删除即可。

代码:

/**
* 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 || head->next==NULL) return head;
ListNode *p= head;
int preval=p->val;
ListNode *pre=p;
p=p->next;
while(p){
if(p->val==preval){
ListNode *t=p;
p=p->next;
pre->next=p;
delete t;
}else{
preval=p->val;
pre=p;
p=p->next;
}
}

return head;
}
};


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
.

题意:跟I 不同之处在于,多次出现的要全部删除。

分析:注意加一个头结点,这样可以处理示例二中,头指针也删掉的情况。

代码:

/**
* 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 || head->next==NULL) return head;
ListNode *hhead=new ListNode(-1);
hhead->next=head;

ListNode *pre=hhead;
ListNode *cur=pre->next;
while(cur && cur->next){
if(cur->val == cur->next->val){

while(cur->next && (cur->val == cur->next->val))
cur=cur->next;

pre->next=cur->next;//pre的next指向修改
cur=cur->next;
}else{
pre=cur; //pre的值修改
cur=cur->next;
}
}
return hhead->next;

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