LeetCode 第 82 题:删除排序链表中的重复元素 II(C++)

82. 删除排序链表中的重复元素 II - 力扣(LeetCode)
在这里插入图片描述
使用哨兵节点简化处理:

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(!head)   return head;
        auto dummy = new ListNode(-1);
        dummy->next = head;
        auto p = dummy, cur = head;
        while(cur && cur->next){
            int flag = 0;
            while(cur->next && cur->val == cur->next->val){
                flag = 1;//置位,表示有相同的值,需要删除
                cur = cur->next;
            }
            if(flag == 0)   p = cur;   
            else p->next = cur->next;
            cur = cur->next;
        }
        return dummy->next;
    }
};

优化一下代码;

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(!head || !head->next)   return head;
        auto dummy = new ListNode(-1);
        dummy->next = head;
        auto pre = dummy, cur = head;
        while(cur && cur->next){
            if(cur->val != cur->next->val){
                pre = cur;
                cur = cur->next;
            }else{
                while(cur->next && cur->val == cur->next->val){
                    cur = cur->next;
                }
                pre->next = cur->next;
                cur = cur->next;
            }
        }
        return dummy->next;
    }
};

如果不使用哨兵节点:

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(!head || !head->next)   return head;
        bool flag = false;//用于标记head是否要去掉
        while(head->next && head->val == head->next->val){
            flag = true;
            head = head->next;
        }
        auto p = head, cur = head;
        while(cur && cur->next){
            if(cur->val != cur->next->val){
                p = cur;
                cur = cur->next;
            }else{
                while(cur->next && cur->val == cur->next->val){
                    cur = cur->next;
                }
                p->next = cur->next;
                cur = cur->next;
            }
        }
        return flag == true ? head->next : head;
    }
};

也可以使用递归或者哈希表处理

  • head 后面有值而且和 head 的值相等,那么就找到不相等为止,然后对后面一个结点去递归,这样就把前面重复的给删除了。
  • head 后面有值但和 head 的值不等,那么就递归后面一个结点,接在 head 的后面

递归不用使用哨兵节点

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(!head || !head->next)   return head;
        if(head->val == head->next->val){
            while(head->next && head->val == head->next->val){
                head = head->next;
            }
            return deleteDuplicates(head->next);
        }
        else head->next = deleteDuplicates(head->next);
        return head;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值