Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
To represent a cycle in the given linked list, we use an integer pos
which represents the position (0-indexed) in the linked list where tail connects to. If pos
is -1
, then there is no cycle in the linked list.
Note: Do not modify the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node.
题意:
找出循环链表的入口
思路
Two Pointers
脑筋急转弯题。没有深究的价值。
code
1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode detectCycle(ListNode head) { 14 ListNode slow = head, fast = head; 15 while (fast != null && fast.next != null) { 16 slow = slow.next; 17 fast = fast.next.next; 18 if (slow == fast) { 19 ListNode slow2 = head; 20 while (slow2 != slow) { 21 slow2 = slow2.next; 22 slow = slow.next; 23 } 24 return slow; 25 } 26 } 27 return null; 28 } 29 }