leetcode82. 删除排序链表中的重复元素 II

慢慢入门了,遇到有的中等可以10分钟内秒了。但是还是很多没有思路或者思路不对,路漫漫其修远兮,吾将上下而求索。
自己写的方法

def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return
        pre = ListNode(0)
        res = pre
        pre.next = head
        while head and head.next:                               #一直重复就没有head了,所以条件加上head,又因为下面判断head.next.val了所以加上和head.next
            if head.val == head.next.val:                       #有重复再进入
                while head.next and head.val == head.next.val:  #一直找到重复节点的最后一位
                    head =head.next
                pre.next = head.next                            #删除所有重复节点,别移动重复的这个指针防止后面还是重复
                head = head.next                                #继续找重复的
            else:
                pre.next = head                                 #没有就正常往下走       
                head = head.next
                pre = pre.next
        return res.next

官解

def deleteDuplicates(self, head):
        if not head or not head.next:
            return head
        dummy = ListNode(0)
        dummy.next = head
        pre = dummy
        cur = head
        while cur:
            # 跳过当前的重复节点,使得cur指向当前重复元素的最后一个位置
            while cur.next and cur.val == cur.next.val:
                cur = cur.next
            if pre.next == cur:  #特别注意!这里判断的是节点是否相同
                 # 如果没有重复的话pre.next就是cur,有重复就会有间隔。pre和cur之间没有重复节点,也就是没有间隔,pre后移
                pre = pre.next
            else:
                # pre->next指向cur的下一个位置(相当于跳过了当前的重复元素)
                # 但是pre不移动,仍然指向已经遍历的链表结尾
                pre.next = cur.next
            cur = cur.next
        return dummy.next
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值