Linked List Cycle II

Linked List Cycle II

问题:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?

思路:

  相遇之后 ,一个指针从头开始,另外一个指针从相遇点开始,再次相遇的时候就是环的开始处

我的代码:

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null || head.next == null)   return null;
        ListNode slow = head, fast = head;
        do
        {
            if(fast == null || fast.next == null)   return null;
            slow = slow.next;
            fast = fast.next.next;
        }while(slow != fast);
        slow = head;
        while(slow != fast)
        {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}
View Code

学习之处:

  • 龟兔赛跑要保持一致起点一致,所以一开始如果List slow = head List fast = head.next; 起点就错了,龟兔的起点不是一致的。
  • do while的作用在此时得到了深刻的体验,龟兔起点一致,为了消除这次起点当成相遇,用了do while,再次相遇才是真正的相遇。
  • 没有环,快指针会首先感知到的。
原文地址:https://www.cnblogs.com/sunshisonghit/p/4322242.html