Problem:
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
.
Analysis:
Solutions:
C++:
ListNode *deleteDuplicates(ListNode *head) {
if(head == NULL)
return head;
ListNode *new_list_head = head;
ListNode *new_list_tail = head;
head = head->next;
new_list_tail->next = NULL;
while(head != NULL) {
if(head->val == new_list_tail->val)
head = head->next;
else {
new_list_tail->next = head;
head = head->next;
new_list_tail = new_list_tail->next;
new_list_tail->next = NULL;
}
}
return new_list_head;
}
Java
:
Python: