-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path82. Remove Duplicates from Sorted List II.cpp
More file actions
100 lines (93 loc) · 2.34 KB
/
Copy path82. Remove Duplicates from Sorted List II.cpp
File metadata and controls
100 lines (93 loc) · 2.34 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* 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;
ListNode *prev = head, *cur = head->next, *res;
int nodecount = 0, flag = 0;
while (cur != NULL)
{
if (cur->val != prev->val)
{
if (flag == 0)
{
if (nodecount == 0)
{
res = prev;
head = prev;
}
else
{
res->next = prev;
res = res->next;
}
nodecount++;
prev = cur;
}
else
{
flag = 0;
prev = cur;
}
}
else
flag = 1;
cur = cur->next;
}
if (nodecount == 0)
{
if (flag == 0)
head = prev;
else
head = NULL;
}
else
{
if (flag == 0)
{
res->next = prev;
res->next->next = NULL;
}
else
res->next = NULL;
}
return head;
}
};
//from Internet
ListNode *deleteDuplicates(ListNode *head)
{
if(head == NULL || head->next == NULL)
{
return head;
}
ListNode *p = new ListNode(-1);
p->next = head;
ListNode *cur = p, *pre = head;
while(pre != NULL)
{
bool isDupli = false;
while(pre->next != NULL && pre->val == pre->next->val)
{
isDupli = true;
pre = pre->next;
}
if(isDupli){
pre = pre->next;
continue;
}
cur->next = pre;
cur = cur->next;
pre = pre->next;
}
cur->next = pre;
return p->next;
}