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?
分析
當fast與slow相遇時,slow肯定沒有遍歷完鏈表,而fast已經在環內循環了n圈(1 \leq n1≤n)。假設slow走了s步,則fast走了2s步(fast步數還等於s加上在環上多轉的n圈),設環長爲r,則:
2s = s + nr
s = nr
設整個鏈表長L,環入口點與相遇點距離爲a,起點到環入口點的距離爲x,則
x + a = nr = (n – 1)r +r = (n-1)r + L - x
x = (n-1)r + (L – x – a)
L – x – a爲相遇點到環入口點的距離,由此可知,從鏈表頭到環入口點等於n-1圈內環+相遇點到環入口點,於是我們可以從head開始另設一個指針slow2,兩個慢指針每次前進一步,它倆一定會在環入口點相遇。

/**
 * 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) {
        ListNode fast = head;
        ListNode slow1 = head;
        while(fast != null && fast.next != null){
            slow1 = slow1.next;
            fast = fast.next.next;
            if(slow1 == fast){
                ListNode slow2 = head;
                while(slow2 != slow1){
                    slow2 = slow2.next;
                    slow1 = slow1.next;
                }
                return slow2;
            }
        }
        return null;
    }
}
發佈了122 篇原創文章 · 獲贊 13 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章