JZ56 删除链表中重复的结点 python

JZ56 删除链表中重复的结点

在这里插入图片描述
错误记录

  1. 1->1->2 头节点可能被删除
  2. 1->1->2->2
  3. 1->1->2->3->3->4->5->5
class Solution:
    def find_no_repeat(self, node):
        p = node
        if p and p.next:
            if p.val != p.next.val:
                return p
            p_no_re = p.next
            while p_no_re and p.val == p_no_re.val:
                p_no_re = p_no_re.next
            return p_no_re
        else:
            return p
    def deleteDuplication(self, pHead):
        # 找到第一个不重复的节点
        p = self.find_no_repeat(pHead)
        while p and p != self.find_no_repeat(p):
            p = self.find_no_repeat(p)
        pHead = p
        while p:
            p_no_re = self.find_no_repeat(p.next)
            while p_no_re and p.next != p_no_re:
                p.next = p_no_re
                p_no_re = self.find_no_repeat(p.next)
            p.next = p_no_re
            p = p_no_re
        return pHead

book method
当前节点是重复节点,则需将上一个节点的next与比当前节点值大的节点相连

class Solution:
    def deleteDuplication(self, pHead):
        # write code here
        newhead = ListNode('a')
        newhead.next = pHead
        pre, cur = None, newhead
        while cur:
            pre = cur
            cur = cur.next
            #判断指针的下一个值是否与当前值相等
            while cur and cur.next and cur.val == cur.next.val:
                t = cur.val
                #和当前值t相等的结点都被抛弃
                while cur and t == cur.val:
                    cur = cur.next
                pre.next = cur
        return newhead.next
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值