Problem:
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
.
Analysis:
Solutions:
C++:
ListNode *deleteDuplicates(ListNode *head) {
if(head == NULL || head->next == NULL)
return head;
for(ListNode* new_head = head->next; ; ) {
if(new_head == NULL)
return NULL;
if(head->val == new_head->val) {
new_head = new_head->next;
continue;
} else {
if(new_head != head->next) {
head = new_head;
new_head = head->next;
if(new_head == NULL || new_head->val != head->val)
break;
} else {
break;
}
}
}
for(ListNode* cur = head; cur != NULL && cur->next != NULL && cur->next->next != NULL;) {
if(cur->next->val != cur->next->next->val) {
cur = cur->next;
continue;
}
ListNode* start = cur->next;
ListNode* end = cur->next->next;
for(; ;) {
if(end == NULL) {
cur->next = NULL;
break;
}
if(end->val == start->val)
end = end->next;
else {
start = end;
end = start->next;
if(end == NULL || end->val != start->val) {
cur->next = start;
break;
}
}
}
}
return head;
}
Java
:
Python: