Sunday, February 28, 2016

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


/**
* 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;
}
};
view raw Q83.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 = 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;
}
};
view raw Q83.cpp hosted with ❤ by GitHub

No comments:

Post a Comment