Leetcode 82. 删除排序链表中的重复元素 II(迭代;递归(非简单的递归))

2021年03月26日 周五 天气晴 【不悲叹过去,不荒废现在,不惧怕未来】


1. 问题简介

82. 删除排序链表中的重复元素 II
在这里插入图片描述

2. 题解

2.1 迭代

求解的关键点在于:当遇到重复元素并删除完了的时候,不要更新pre ,因为可能cur->next还是重复的节点;只有当cur->valcur->next->val不相等时(保证了cur一定不是重复的节点),才更新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 递归

这道题递归还真的没有迭代简单,具体思路如下:
在这里插入图片描述

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;
    }
};

参考文献

https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/solution/fu-xue-ming-zhu-di-gui-die-dai-yi-pian-t-wy0h/

猜你喜欢

转载自blog.csdn.net/m0_37433111/article/details/115256172