美文网首页
python实现leetcode之141. 环形链表

python实现leetcode之141. 环形链表

作者: 深圳都这么冷 | 来源:发表于2021-10-14 00:08 被阅读0次

解题思路

快慢指针,快指针上一步落后1,这一步就跟上了,不会完美错过
所以,如果有环,快慢指针总会相遇

141. 环形链表

代码

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        fast = slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow: return True
        return False
效果图

相关文章

网友评论

      本文标题:python实现leetcode之141. 环形链表

      本文链接:https://www.haomeiwen.com/subject/tipdoltx.html