Method for Determining whether a Linked List has a ring or a ring entry point (Linked List Cycle II)
Two steps
The first step is to use the speed pointer. If there is a ring, the speed pointer will eventually meet on a node.
Step 2. Then, start from this node and take a step at the same time from the root node. The place where the two pointers meet is the entrance of the ring.
The first step explains why the second step is?
There are many solutions on the Internet that are mostly analyzed from the mathematical point of view, and there are formulas and calculations that are not intuitive. From the graphic point of view, it is much easier to understand.
Spread the graph into a line. If we have a ring and assume that the fast pointer goes through one more lap, it will be the same as the slow pointer (n more laps are actually the same. It is not hard to understand the plot, it is represented by a circle when it is difficult to draw)
The red line indicates that the fast pointer has gone through the 2 m blue line, indicating that the slow pointer has gone through m, which can be intuitively seen. If you move the Blue Line to the red line above, the red line will be blocked, the number of remaining red lines
It is a y and a z. We know that the length of the multiple steps is m, that is, y + z = m. The blue line is also m, that is, x + z = m.
So if we launch x = y directly, we will understand the second step. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + PGJyPgo8L3A + CjxwPsjnufvLtb/fingerprint + bV4rj2zby1xMSj0M3Jz8C0oaM8L3A + CjxwPjxpbWcgc3JjPQ = "alt = "\
Code Attached
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode detectCycle(ListNode head) { if(head==null){ return null; } ListNode slow = head; ListNode fast = head; ListNode now = head; while(fast.next!=null&&fast.next.next!=null){ fast = fast.next.next; slow = slow.next; if(fast==slow){ now = slow; break; } } if(fast.next==null||fast.next.next==null) return null; else{ ListNode start = head; while(start!=now){ start = start.next; now = now.next; } return start; } }}