Title:
Given A linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Tips:
First, the topic requires ' without using extra space ', which means that the spatial complexity must be controlled within O (1).
Therefore, you can create two variables, point to head at the same time, and then each cycle, so that one of the variables along the linked list forward "walk" two steps, the other "step", so that each cycle after each of their distance will be +1.
If there is a loop in the chain, then this circuit is equivalent to a modulo operation, when the distance between the two is equal to the length of the circuit, it means that has met. So these two variables will eventually meet in a certain step, and this time we can determine the loop.
Conversely, if there is no circuit, then the faster the "walk" of the variable will be the first to go to null, this time can be judged no circuit.
Code:
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: BOOLHascycle (ListNode *head) {ListNode*fast =Head; ListNode*slow =Head; while(Fast && fast->next) {Fast= fast->next->Next; Slow= slow->Next; if(Fast = =slow)return true; } return false; }};
"Leetcode" 141. Linked List Cycle