forked from fanfank/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove-duplicates-from-sorted-list.cpp
50 lines (49 loc) · 1.37 KB
/
remove-duplicates-from-sorted-list.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
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(head == NULL)
return head;
ListNode *h = head, *p = head, *del = NULL;
while(p->next != NULL) {
if(p->next->val == head->val) {
del = p->next;
p->next = del->next;
delete del;
}
else {
head = p->next;
p = head;
}
}
return h;
}
};
//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;
while((*pCur)->next) {
if((*pCur)->next->val == (*pCur)->val) {
del = (*pCur)->next;
(*pCur)->next = del->next;
delete del;
} else {
pCur = &((*pCur)->next);
}
}
return head;
}
};