Leetcode141. Determine if there is a ring in the linked list
Idea: Set the fast and slow dual pointers, the slow pointer +1 is the fast pointer +2. If it does not contain a ring, the fast pointer will eventually encounter null, indicating that the linked list does not contain a ring; if it contains a ring, the fast pointer will eventually be a super slow pointer, and meet the slow pointer, indicating that the linked list contains a ring. The time complexity is O (n).
Leetcode142. Determine the ring entry of the linked list
Idea: double pointer; the same as the simple problem of the ring list . When the first and the fast pointer (1) meet, there is fast = slow + k ring length and fast = 2 slow to get slow = k ring length. Note: Assuming that a pointer can go a step from the head of the linked list to the ring entry node, then the number of steps from the head of the linked list to the ring entrance is a + k ring length, so slow can be reached by a step after the first intersection After the first two pointers meet in the ring entrance (2), let the fast node point back to the head of the linked list. Then the fast and slow pointers move forward synchronously, so as to ensure that when the second encounter, the fast and slow pointers just point to the ring entrance
public ListNode detectCycle(ListNode head){if(head==null)return null;
ListNode slow = head;
ListNode fast = head;while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;if(fast == slow)break;}
fast = head;//快指针指回头结点while(slow!=fast){//第二次相交前快慢指针都一步步走
fast = fast.next;
slow = slow.next;}return slow;}