forked from fanfank/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremove-duplicates-from-sorted-list-ii.cpp
68 lines (65 loc) · 1.94 KB
/
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
59
60
61
62
63
64
65
66
67
68
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool judgeDuplication(ListNode *cur) {
if(cur->next == NULL)
return false;
return (cur->val == cur->next->val);
}
ListNode *deleteDuplicates(ListNode *head) {
// Note: The Solution object is instantiated only once and is reused by each test case.
//create a dummy head
ListNode *dh = new ListNode(0);
dh->next = head;
ListNode *p = dh, *del = NULL;
//judge duplications and delete
while(p->next != NULL) {
if(judgeDuplication(p->next)) {
int last = p->next->val;
while(p->next != NULL && p->next->val == last) {
del = p->next;
p->next = del->next;
delete del;
}
}
else {
p = p->next;
}
}
del = dh;
dh = dh->next;
delete del;
return dh;
}
};
//used a second level pointer
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(head == NULL)
return head;
ListNode **pCur = &head, *del = NULL;
int last;
while((*pCur) != NULL && (*pCur)->next != NULL) {
if((*pCur)->next->val == (*pCur)->val) {
last = (*pCur)->val;
while((*pCur) != NULL && (*pCur)->val == last) {
del = *pCur;
*pCur = del->next;
delete del;
}
} else {
pCur = &((*pCur)->next);
}
}
return head;
}
};