First, the original question
Linked List Cycle
Given A linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Second, analysis
Choose two pointers to scan the linked list, a fast speed, a slow, if two pointers meet, indicating a ring.
Third, code (Java)
/** * Definition for singly-linked list. * Class ListNode {* int val; * ListNode Next; * listnode (int x) {* val = x; * next = null; * } * } */public Class Solution {public Boolean hascycle (ListNode head) { boolean result=false;if (head==null| | Head.next==null) {}else{ listnode fast,slow; Slow=head; Fast=head; while (Fast!=null) { if (fast.next==null| | Fast==null) break ; else{ Fast=fast.next.next; Slow=slow.next; } if (fast==slow) {result=true; break;}} } return result;} }
Four
About the speed of the meeting indicates the link list has a ring proof:
http://umairsaeed.com/2011/06/23/finding-the-start-of-a-loop-in-a-circular-linked-list/.
More intuitive explanation, if two points in a circle running, the same direction, as long as the speed is not the same will meet, in the straight line is not necessarily.
"Leetcode" Linked List Cycle