-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path82_Remove Duplicates from Sorted List II.cpp
58 lines (52 loc) · 1.54 KB
/
82_Remove Duplicates from Sorted List II.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if ( head == NULL || head->next == NULL )
return head;
else if ( head->val == head->next->val && head->next->next == NULL )
return NULL;
ListNode* cur = head->next;
ListNode* prev = head;
while ( cur!= NULL ) {
bool duplicate = false;
// if the first sequence of nodes are the same
while ( prev->val == cur->val ) {
cur = cur->next;
if ( cur == NULL )
return NULL;
duplicate = true;
}
if ( duplicate ) {
if ( prev == head ) {
head = cur;
prev = cur;
cur = cur->next;
if ( cur == NULL )
break;
continue;
}
}
while ( cur->next != NULL && cur->val == cur->next->val ) {
cur = cur->next;
duplicate = true;
}
if ( duplicate ) {
prev->next = cur->next;
cur = cur->next;
}
else {
cur = cur->next;
prev = prev->next;
}
}
return head;
}
};