【LEETCODE】142-Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:

Can you solve it without using extra space?


参考:

http://fisherlei.blogspot.jp/2013/11/leetcode-linked-list-cycle-ii-solution.html




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

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None or head.next is None:
            return None
        
        slow=head.next           #第一步错开,否则下面的while slow!=fast不会进行
        fast=head.next.next
        
        while fast and fast.next and slow!=fast:
            slow=slow.next
            fast=fast.next.next
        
        if fast is None or fast.next is None:      #无环
            return None
        
        slow=head                 #用slow记录x长度
        while slow!=fast:         #下次相遇一定在环的始点,并且slow和fast都走了x步
            slow=slow.next
            fast=fast.next
        return slow


你可能感兴趣的:(【LEETCODE】142-Linked List Cycle II)