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;
}
};
相关文章推荐
- LeetCode 之 Remove Duplicates from Sorted List I II — C++ 实现
- Remove Duplicates from Sorted List I II -- leetcode
- 082&083 Remove Duplicates from Sorted List I II [Leetcode]
- LeetCode Remove Duplicates from Sorted List
- LeetCode(82)Remove Duplicates from Sorted List
- 78 leetcode - Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List II
- 83. Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List I
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [leetcode oj 83]Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List(去除有序链表中的重复元素)
- LeetCode Remove Duplicates from Sorted List II
- Leetcode Remove Duplicates from Sorted List
- lintcode 容易题:Remove Duplicates from Sorted List 删除排序链表中的重复元素
- FTPrep, 82 Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- leetcode:Remove Duplicates from Sorted List II