/**************************************************************************
*
* 82. [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)
*
* Given the head of a sorted linked list, delete all nodes that have duplicate numbers,
* leaving only distinct numbers from the original list. Return the linked list sorted as well.
*
* Example 1:
* Input: head = [1,2,3,3,4,4,5]
* Output: [1,2,5]
*
* Example 2:
* Input: head = [1,1,1,2,3]
* Output: [2,3]
**************************************************************************/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode NODE;
///
///
/// Approach 1
NODE *deleteDuplicates(NODE *head){
if (NULL == head || NULL == head->next) return head;
NODE dum;
dum.next = head;
NODE *pre = &dum;
NODE *cur = head;
while (head) {
if (head->next != NULL && head->val == head->next->val) {
while (head->next != NULL && head->val == head->next->val)
head = head->next;
pre->next = head->next;
} else
pre = pre->next;
head = head->next;
}
return dum.next;
}
///
///
/// Approach 2
NODE *deleteDuplicates(NODE *head){
if (NULL == head || NULL == head->next) return head;
NODE *next = head->next;
if (head->val == next->val) {
while (next && head->val == next->val) {
NODE *del = next;
next = next->next;
free(del);
}
free(head);
return deleteDuplicates(next);
} else {
head->next = deleteDuplicates(head->next);
return head;
}
}
///
///
/// Approach 3
NODE *deleteDuplicates(NODE *head){
if (NULL == head || NULL == head->next) return head;
NODE dum;
NODE *pre = &dum;
NODE *cur = head;
while (cur) {
char duplicated = 0;
while (cur->next && cur->val == cur->next->val) {
duplicated = 1;
NODE *del = cur;
cur = cur->next;
free(del);
}
if (duplicated) {
NODE *del = cur;
cur = cur->next;
free(del);
continue;
}
pre->next = cur;
pre = cur;
cur = cur->next;
}
pre->next = cur;
return dum.next;
}