leetcode141. 环形链表 & 142 环形链表 II

def hasCycle(self, head):
        """
        注意边界越界的问题
        设置一个快指针和慢指针,慢指针和快指针相遇就存在环,如果有存在节点的next为None的情况没有环。
        """
        if not head:
            return False
        if not head.next or not head.next.next:
            return False
        s = head.next
        f = head.next.next
        while f and s:
            if f == s:
                return True
            elif not f.next or not s.next:###边界越界
                return False
            else:
                s = s.next
                f = f.next.next
                
        return False

leetcode 142

def detectCycle(self, head):
        """
        在141基础上先判断是否存在环(快慢指针)
        如果存在环,继续把快指针=head,快指针走一步,继续走下去,直到相遇点就是环的入口点
        """
        if not head:
            return None
        if not head.next or not head.next.next:
            return None
        s = head.next
        f = head.next.next
        flag = 0
        while f and s:
            if f == s:
                break
            elif not f.next or not s.next:###边界越界
                return None
            else:
                s = s.next
                f = f.next.next
        '''
        边界条件注意
        '''
        if s == f and f.next:
            f = head
            while f != s:
                s = s.next
                f = f.next
            return f
            
        return None

为什么是快指针是慢指针的两倍速度,为什么入口点是相遇之后放慢快指针再次相遇的点,参考

https://blog.csdn.net/xy010902100449/article/details/48995255

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值