leetcode-82-remove duplicates from sorted list ii

题目

给定一个排好续的链表,删除链表中重复的元素

分析

举例说明:
输入: 1-2-3-3-4-4-5
返回: 1-2-5
考虑特殊情况1-1-1,1-2-2,1-2-2-3,1-2-2-3-3

C++代码实现

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

* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/

class Solution {
public:
ListNode* (ListNode* head) {
if(!head || !head->next) return head;
ListNode * res;
ListNode first(0);
res = &first;
res->next = head;
ListNode *pre = res;
ListNode *cur = head;

bool dup = false;
while(cur != NULL)
{
while(cur->next != NULL && cur->next->val == cur->val)
{
cur = cur->next;
dup = true;
}
if(dup && cur->next == NULL) //针对{1,1,2,2}{1,1}的情况
{
pre->next = cur->next;
pre = pre->next;
}
if(!dup)
{
pre->next = cur;
pre = pre->next;
}
dup = false;
cur = cur->next;
}
return res->next;
}
};