Friday, February 26, 2016

LeetCode Q82: 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.

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.

/**
* 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;
}
};
view raw Q82-1.cpp hosted with ❤ by GitHub
Round 2 solution:
/**
* 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;
}
};
view raw Q82-2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment