Leetcode problem Solving linked List Cycle II original question
If a loop exists in the given unidirectional list, the position of the loopback start is returned, otherwise the return is empty. It is best not to apply for extra space.
Note the point:
- Do not modify the linked list
Example:
Input:
1->2->3 | | 5<-4
Output: 2
Thinking of solving problems
In [Linked list Cycle] (141 Linked list cycle.md), we use a double pointer method to determine whether a loop exists in a linked list. On this basis, we will find the starting node of the ring. As shown, suppose that the starting node of the list is a, the starting node of the ring is B, and the fast and slow pointer meets at C. Because the fast pointer speed is twice times the slow pointer, so in the same time, it walked the distance is twice times the slow pointer, and the fast pointer through the distance is (x+y+z+y), and the slow pointer through the distance is (x+y), according to the relationship we can get x+y+z+y = 2(x+y) , that is x=z . At this point, the speed pointer at C, the head pointer at a, and their distance to B is equal, so long as there are two pointers from point A and point C at the same speed forward will meet at point B, that is to find the ring of the starting node.
Note: The above situation is ideal, in fact, when the point C met, the fast pointer may have been around the ring for several laps, such as AB is very long, and the ring is very small situation. Assuming that the N-circle is gone, the equation is, that is, the x+y+n(z+y) = 2(x+y) x=(n-1)(y+z)+z distance from the point C around the n-1 circle and then the z is followed by a pointer from point A to meet at point B.
AC Source
# 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 "" "Slow = Fast = Head whileFast andFast.next:slow = Slow.next Fast = Fast.next.nextifslow = = Fast:node = Head whileNode! = Slow:node = Node.next Slow = Slow.nextreturnNodereturn Noneif__name__ = ="__main__":None
Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.
Leetcode Linked List Cycle II