Leetcode problem Solving linked List cycle original problem
Determine if there is a link in a list, can you complete it without applying for additional space?
Note the point:
Example:
Input:
1->2->3 | | 5<-4
Output: True
Thinking of solving problems
Continuous traversal along the linked list indicates that the linked list does not exist if a null node is encountered. But if there is a loop, such a traversal will go into the dead loop. Forward on the ring will continue to circle around, we let two different speed of the pointer around the ring forward, then sooner or later the speed of the faster that will catch up slow, so if the speed of catching up with slow, then the list of the existence of the ring, the cycle of termination.
AC Source
# 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 "" "Slow = Fast = Head whileFast andFast.next:slow = Slow.next Fast = Fast.next.nextifslow = = Fast:return True return Falseif__name__ = ="__main__":None
Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.
Leetcode Linked List Cycle