Fork me on GitHub

Remove Duplicates from Sorted List II

Description

https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool duplicate(struct ListNode* node) {
if (node == NULL || node->next == NULL) return false;
return node->val == node->next->val;
}


struct ListNode* deleteDuplicates(struct ListNode* head) {
if (head == NULL || head->next == NULL) return head;

struct ListNode* setinel_head = (struct ListNode* ) malloc(sizeof(struct ListNode));
setinel_head->next = head;


struct ListNode* pre = setinel_head;
struct ListNode* current = head;
while (current != NULL) {
if (duplicate(current) == false) {
pre = pre->next;
current = pre->next;
}else {
struct ListNode* nextNode = current->next;
while (nextNode != NULL && current->val == nextNode->val){
nextNode = nextNode->next;
}
pre->next = nextNode;
current = nextNode;
}
}
return setinel_head->next;
}