82. Remove Duplicates from Sorted List II

每日一题 2019 - 04 - 16

题目:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

1
2
Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

1
2
Input: 1->1->1->2->3
Output: 2->3

解答:

这个题需要去除链表中所有重复的元素(只要重复该元素全部清除),思路比较直观也比较简单:

  • 开一个 vector 用来存放不重复的元素
  • 每次遍历链表时候判断当前位置的元素是否与 vector 顶端的元素相同,如果相同就跳过,且最后弹出 vector 最尾部元素
  • 最后需要注意,如果 vector 中一个元素也不存在,那么直接将 head 置空返回

代码:

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
/**
* 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 )
{
return head ;
}
ListNode *temp = head ;
vector<int> now ;
now.push_back(temp -> val) ;
temp = temp -> next ;
while( temp != NULL )
{
if(now.size() == 0)
{
now.push_back(temp->val);
temp = temp -> next ;
continue ;
}
if(now[now.size()-1] == temp-> val)
{
while(now[now.size()-1] == temp-> val && temp != NULL)
{
temp = temp -> next ;
if(temp == NULL)
{
break ;
}
}
now.pop_back();
}
else if(now[now.size()-1] != temp -> val)
{
now.push_back(temp->val);
temp = temp -> next ;
}
}
temp = head ;
ListNode *before = NULL ;
for(int i = 0 ; i < now.size() ; i ++)
{
temp -> val = now[i] ;
before = temp;
temp = temp ->next ;
}
if(now.size() == 0)
{
head = NULL ;
return head ;
}
before -> next = NULL;
return head ;
}
};
0%
undefined