Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given
Given
Given
1->2->3->3->4->4->5
, return 1->2->5
.Given
1->1->1->2->3
, return 2->3
.
Solution 1 (Non-recursive)
Compare value of current node and next node. Be careful to check if next node is NULL ahead. Also, be careful of some corner case such as:
[1, 1, 2]: Need to create a new head node in front of the first node.
[1, 1]: Need to create a new head node in front of the first node.
[1]: Need to create a new head node in front of the first node.
[1, 2, 2, 3, 3]: when duplicate numbers are one after another, need to double check whether the first non identical number is a new start of next group of duplicate numbers.
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) { | |
ListNode* newHead=new ListNode(-1); | |
newHead->next=head; | |
ListNode* pre=newHead; | |
ListNode* cur=head; | |
bool dup=false; | |
while(cur!=NULL){ | |
dup=false; | |
while(cur!=NULL&&cur->next!=NULL){ | |
if(cur->val==cur->next->val){ | |
dup=true; | |
cur=cur->next; | |
}else | |
break; | |
} | |
cur=(dup==true)?cur->next:cur; | |
if(cur==NULL){ | |
pre->next=cur; | |
ListNode* tmpHead=newHead->next; | |
delete newHead; | |
return tmpHead; | |
} | |
if(cur->next!=NULL){ | |
if(cur->val==cur->next->val) | |
continue; | |
} | |
pre->next=cur; | |
pre=cur; | |
if(cur!=NULL) | |
cur=cur->next; | |
} | |
ListNode* tmpHead=newHead->next; | |
delete newHead; | |
return tmpHead; | |
} | |
}; |
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=head; | |
ListNode* nn=n->next; | |
while(nn!=NULL){ | |
if(nn->val!=n->val){ | |
p=p->next; | |
n=p->next; | |
nn=n->next; | |
}else{ | |
while(nn!=NULL&&n->val==nn->val){ | |
n=n->next; | |
nn=n->next; | |
} | |
p->next=nn; | |
n=p->next; | |
nn=n==NULL? NULL:n->next; | |
} | |
} | |
return newHead->next; | |
} | |
}; |
No comments:
Post a Comment