-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveDuplicatesFromSortedListII.h
54 lines (51 loc) · 1.18 KB
/
RemoveDuplicatesFromSortedListII.h
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
*Solution 1
*iterative
*time:O(n) space:O(1)
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
ListNode dummy=(0),*pre=&dummy;
dummy.next=head;
while(pre&&pre->next)
{
ListNode *first=pre->next;
ListNode *second=pre->next->next;
bool flag=true;
if(second&&second->val==first->val)flag=false;
while(second&&second->val==first->val)second=second->next;
if(!flag)pre->next=second;
else pre=pre->next;
}
return dummy.next;
}
};
/**
*Solution 2
*recursive
*time:O(n) space:O(1)
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(!head||!head->next)return head;
ListNode *p=head->next;
if(p->val==head->val)
{
while(p&&p->val==head->val)p=p->next;
delete head;//勿忘
return deleteDuplicates(p);
}
head->next=deleteDuplicates(p);
return head;
}
};