python实现leetcode之141. 环形链表

2021-10-14  本文已影响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
效果图
上一篇 下一篇

猜你喜欢

热点阅读