82. Remove Duplicates from Sorted List II**
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
题目描述
Given 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: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
C++ 实现 1
使用 [pre, next)
来标注值相同的节点, 如果 pre->next == next
, 说明 pre
是 unique 的, 应该加入到 dummy
链表中. 另外一道删除重复节点的题在 206. Reverse Linked List* .
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head || !head->next) return head;
ListNode* dummy = new ListNode(0);
auto p = dummy;
auto pre = head, next = head->next;
auto value = pre->val;
while (next) {
if (next->val == value) {
next = next->next;
} else {
if (pre->next == next) {
p->next = pre;
p = p->next;
}
pre = next;
next = next->next;
value = pre->val;
}
}
p->next = pre->next ? nullptr : pre;
head = dummy->next;
return head;
}
};