Leetcode Tag Search | Back

Fast and slow pointers

Category: /template

Template

Explaination Details Template Index
def meet(self, head):
    """ check whether there is a cycle """
    if not head: return None
    slow = head
    fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast: return slow
    return None

def detect_cycle(self, head):
    """ if there is a cycle, return the node that cycle begins """
    fast = self.meet(head)
    if not fast: return None
    slow = head
    while slow != fast:
        if not fast or not fast.next: 
            return None
        slow = slow.next
        fast = fast.next
    return slow

讨论

提示

  • 如果看不到讨论部分, 请暂时关掉adblock in Firefox/Chrome
  • 本网站使用Javascript实现评论功能, 此处外链对提高您的网站PR没有帮助. (潜台词: 请不要灌水, 谢谢)