Friday, March 26, 2021, the weather is fine [Don’t lament the past, don’t waste the present, don’t fear the future]
Contents of this article
1. Introduction
82. Delete duplicate elements in the sorted list II
2. Solution
2.1 Iteration
The key point of the solution is: when you encounter duplicate elements and delete them, do not update pre
, because they may cur->next
still be duplicate nodes; only update when the cur->val
sum is cur->next->val
not equal (to ensure that cur
it is not a duplicate node) pre
.
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* preHead = new ListNode(0);
preHead->next = head;
ListNode* pre = preHead, *cur = head;
while(cur && cur->next){
// 遇到重复元素,就彻底“消灭”它
if(cur->val==cur->next->val) {
int a = cur->val;
while(cur->next && cur->next->val==a) cur = cur->next;
pre->next = cur->next; // pre 不更新,因为可能 cur->next 还是重复的节点
}
else pre = pre->next; // 只有当 当前节点 和 下一节点 不相等时,才更新 pre
cur = cur->next;
}
return preHead->next;
}
};
2.2 Recursion
The recursion of this question is really not as simple as iterative. The specific ideas are as follows:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head==nullptr || head->next==nullptr) return head;
if(head->val!=head->next->val){
head->next = deleteDuplicates(head->next);
}
else{
ListNode* move = head->next;
while(move && move->val==head->val) move = move->next;
return deleteDuplicates(move);
}
return head;
}
};
references
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/solution/fu-xue-ming-zhu-di-gui-die-dai-yi-pian-t-wy0h/