//from anniekim, iterative
ListNode *deleteDuplicates(ListNode *head) {
ListNode dummy(0);dummy.next=head;
ListNode *prev=&dummy;
while(prev->next){
int val=prev->next->val;
ListNode *node=prev->next;
if(!node->next||node->next->val!=val){
prev=prev->next;
continue;
}
while(node&&node->val==val){
ListNode*del=node;
node=node->next;
delete del;
}
prev->next=node;
}
return dummy.next;
}
//recursive
ListNode *deleteDuplicates(ListNode *head) {
if (!head) return NULL;
if (!head->next || head->val != head->next->val) {
head->next = deleteDuplicates(head->next);
return head;
}
int val = head->val;
while(head && head->val == val) {
ListNode *del = head;
head = head->next;
delete del;
}
return deleteDuplicates(head);
}
No comments:
Post a Comment