Remove Duplicates from Sorted List II [LeetCode]

时间:2023-03-08 17:49:44

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.

Solution:

     ListNode *deleteDuplicates(ListNode *head) {
if(head == NULL || head->next == NULL)
return head; //remove the head
ListNode * same_node = NULL;
while(head != NULL) {
if(same_node == NULL) {
if(head->next != NULL && head->val == head->next->val){
same_node = head;
head = head->next;
}else {
break;
}
}else {
if(head->val == same_node->val)
head = head->next;
else
same_node = NULL;
}
} if(head == NULL || head->next == NULL)
return head; ListNode * pre = head;
ListNode * same = NULL;
ListNode * current = pre->next;
while(current != NULL) {
if(same == NULL) {
if(current->next != NULL && current->val == current->next->val){
same = current;
pre->next = current->next;
}else{
pre = pre->next;
}
current = current->next;
}else {
if(current->val == same->val){
pre->next = current->next;
current = current->next;
}else {
same = NULL;
}
}
} return head;
}