解题思路
快慢指针,快指针上一步落后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
效果图
网友评论