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
.
<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>
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
.
<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>
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
.
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);
}