142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
题意:
在142. Linked List Cycle II的基础上,找到环起点的位置。
就是利用287. Find the Duplicate Number的思路,在287题的基础上,判断是否会 不能构成环 即可。具体思路可以去看一下 287题
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) return null;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if (fast == slow)
break;
}
if (fast == null || fast.next == null) return null;
fast = head;
while (fast != slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}