[LeetCode] Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull
.
Follow up:
Can you solve it without using extra space?
First, set the ring length to r. When the distance from the ring port to a is met, and the distance from the outer ring is B, there is 2 (a + B) = a + B + nr, n> 1;
So there is a + B = nr; Further there are B + pr = (r-a) + qr, that is, the pointer from the beginning and the pointer from the current encounter position must move at the same speed at the ring port position.
/** * 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 slow2 = head;ListNode slow = head;ListNode fast = head;boolean isCycle = false;while(fast!=null&&fast.next!=null){slow = slow.next;fast = fast.next.next;if(slow == fast) {isCycle = true;break;}}if(isCycle){while(slow2!=slow){slow = slow.next;slow2 = slow2.next;}return slow;}else{return null;}}}