Given A linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
To solve this problem requires a very clever idea, generally we would think of observing whether the linked list has repeated occurrences of the node. However, the complexity of this space is O (n), such as set to store the occurrence of the node, and then see if the next node exists in the set.
A very ingenious solution is to set two pointers, a fast pointer, and a slow pointer. The quick pointer moves two steps at a time, and the slow pointer moves one step at a time. Assuming that two pointers are starting from one node of the ring at the same time, the length of the ring is N. Since the fast pointer is faster than the slow pointer each time, so at most n times the fast pointer moves more than the slow pointer n times, just over the slow pointer One ring, that is, the N word movement after two pointers will definitely meet. And regardless of whether the two pointers are from the same node of the ring, two pointers will meet after M-move, and M<=n (M refers to the number of pointer movements on the ring, because the first half of the list may not be on the ring, so the time of two pointers to the nodes on the ring will be different, the fast pointer will arrive first, Arrives after a slow pointer). The code is as follows:
1 Public classSolution {2 Public Booleanhascycle (ListNode head) {3ListNode slow =head;4ListNode fast =head;5 6 while(slow!=NULL&& fast!=NULL){7slow =Slow.next;8Fast =Fast.next;9 if(fast!=NULL) Fast =Fast.next;Ten Else return false; One if(slow = = fast)return true; A } - return false; - } the}
Leetcode OJ 141. Linked List Cycle