Linked List Cycle II
思路
- 使用九章算法的方法, 但是老是记不住! 总是搞混.
- 再次复习一遍, 有circle就说明slow/fast会相遇. 等到相遇后, 将slow重置为head, 那么当
slow == fast.next
的时候, slow的位置就是cycle入口.
idea
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode fast = head.next , slow = head;
while (fast != slow) {
if (fast == null || fast.next == null) return null;
fast = fast.next.next;
slow = slow.next;
}
slow = head;
while (fast.next != slow) {
fast = fast.next;
slow = slow.next;
}
return slow;
}