Remove Duplicates from Sorted List I
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.
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* rst=new ListNode(0);
rst->next=head;
ListNode* p1=rst;
ListNode* p2=head;
while(p2){
while(p2->next&&p2->next->val==p2->val){
p2=p2->next;
}
p1->next=p2;
p1=p2;
p2=p2->next;
}
p1->next=p2;
ListNode* tmp=rst->next;
delete rst;
return tmp;
}
};
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.
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode *rst=new ListNode(10000);
rst->next=head;
ListNode *p1=rst;
ListNode *p2=head;
while(p2){
bool dup=false;
while(p2->next&&p2->next->val==p2->val){
dup=true;
p2=p2->next;
}
if(dup==true){
p2=p2->next;
continue; //如果有重复那么跳过
}
p1->next=p2;
p1=p2;
p2=p2->next;
}
p1->next=p2;
ListNode *tmp=rst->next;
delete rst;
return tmp;
}
};