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
.
ListNode* deleteDuplicates(ListNode* head)
{
if(head == NULL || head->next == NULL) return head;
ListNode *res = new ListNode(-1);
res->next = head;
ListNode *r = res, *p = head;
while(p != NULL)
{
bool same = false;
while(p->next != NULL && p->val == p->next->val)
{
same = true;
p = p->next;
}
if(same == true)
{
p = p->next;
continue;
}
r->next = p;
r = r->next;
p = p->next;
}
r->next = p;
return res->next;
}