-
Notifications
You must be signed in to change notification settings - Fork 1
/
018_02-在O(1)时间删除链表结点.cpp
47 lines (45 loc) · 1.11 KB
/
018_02-在O(1)时间删除链表结点.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
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if(pHead==nullptr)
return nullptr;
ListNode* node=pHead;
ListNode* front=nullptr;
ListNode* pnext;
while(node!=nullptr){
bool needDel=false;
pnext=node->next;
if(pnext!=nullptr&&node->val==pnext->val)
needDel=true;
if(!needDel){
front=node;
node=pnext;
}else{
int val=node->val;
ListNode* toDel=node;
while(toDel!=nullptr&&toDel->val==val){
pnext=toDel->next;
delete toDel;
toDel=nullptr;
toDel=pnext;
}
if(front==nullptr)
pHead=pnext;
else
front->next=pnext;
node=pnext;
}
}
return pHead;
}
};