Determine if a list exists in a loop (not a Val loop), that is, imagine a ring, the ring may also be connected to a line, now to determine whether the linked list contains this ring.
Set the speed of two nodes, slow one step, fast two steps, if there is a ring, then slow and fast will certainly enter this ring, it is now proven that once into the ring slow and fast will inevitably meet in the loop.
The position of the slow in the ring is X,fast y, the ring has a m position and is set through n loops, and the slow position is now x+n,fast y+2n. Slow and fast Equals (x+n)%m = (y+2n)%m, set x+n = am+b, y+2n = Cm+d,slow and fast meet B=d, two equations subtract n= (c-a) m+x-y=am+x-y, That there must be some n that makes slow and fast meet.
If there is a ring then return true if slow and fast meet, otherwise the while loop ends with return false.
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: One BOOLHascycle (ListNode *head) { Alistnode* slow = head, * fast =head; - while(Fast && fast->next && fast->next->next) { -slow = slow->Next; theFast = Fast->next->Next; - if(Fast = = slow)return true; - } - return false; + } -};
Leetcode 141. Linked List Cycle