Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
Given
1->1->2
, return 1->2
.Given
1->1->2->3->3
, return 1->2->3
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) | |
return head; | |
ListNode* newHead=new ListNode(-1); | |
newHead->next=head; | |
ListNode* p0=head; | |
ListNode* p1=head; | |
while(p0->next!=NULL){ | |
if(p1==NULL){ | |
p0->next=NULL; | |
break; | |
} | |
if(p0->val==p1->val){ | |
p1=p1->next; | |
}else{ | |
p0->next=p1; | |
p0=p1; | |
} | |
} | |
head=newHead->next; | |
delete newHead; | |
return head; | |
} | |
}; |
Round 2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) | |
return NULL; | |
ListNode* newHead = new ListNode(head->val+1); | |
newHead->next=head; | |
ListNode* p = newHead; | |
ListNode* n = p->next; | |
while(n!=NULL){ | |
if(p->val!=n->val){ | |
p=p->next; | |
n=p->next; | |
}else{ | |
while(n!=NULL&&n->val==p->val){ | |
n=n->next; | |
} | |
p->next=n; | |
} | |
} | |
return newHead->next; | |
} | |
}; |
No comments:
Post a Comment