题目
原题在此
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Example 1:
Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]
Example 2:
Input: head = [1,1,1,2,3]
Output: [2,3]
Constraints:
- The number of nodes in the list is in the range [0, 300].
- -100 <= Node.val <= 100
- The list is guaranteed to be sorted in ascending order.
解析
- 与Remove Duplicates from Sorted List I不同之处在于,这次要将重复值一个不留完全移除.
- 有head的值会重复的情况,所以
new
一个值与head不一样的dummy指向head; - 声明两个指针, p1指向dummy, p2指向head;
- 当p2不为空时,
- 当p2有next且next的值和p2相等时,p2指向next;
- 此时有两种情况,p1和p2挨着,两个指针分别指向自己的next. 否则p2指向自己的next,p1指向p2.此时便跳过了重复的值
代码
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/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head) return head;
ListNode dummy(head->val + 1, head);
ListNode* p1 = &dummy, *p2 = head;
while(p2) {
while(p2 -> next && p2 -> val == p2 -> next -> val) {
p2 = p2 -> next;
}
if(p1 -> next == p2) {
p1 = p2;
p2 = p2 -> next;
} else {
p2 = p2 -> next;
p1 -> next = p2;
}
}
return dummy.next;
}
};