1. 程式人生 > >LeetCode-141 linked list cycle 環形連結串列

LeetCode-141 linked list cycle 環形連結串列

題目連結

LeetCode-141 linked list cycle

題意

據說也是面試經典連結串列題了,判定是否存在環。以此還可以引申很多連結串列相關題,可以去搜一下,或者看我的部落格:

https://blog.csdn.net/iwts_24/article/details/83421853

題解

        其實是比較簡單的,因為判定有環的情況下,一直next向下跑是死迴圈,但是例如高中經典物理題追及問題,一個人速度快一個人速度慢,那麼最終是一定會相遇的。我們也可以設定兩個指標,一個每次1速向後遍歷,另外一個2速遍歷,那麼如果無環,最終快指標是會成為NULL,而如果有環,那麼快指標一定會在某個過程中與慢指標相遇。

        這個題有一點注意,fast.next.next。快指標最好不要這樣寫,因為如果fast是連結串列尾(無環的情況),那麼fast.next = null,這樣呼叫fast.next.next會丟擲異常。所以應該先判定fast.next是否為null。

Java 程式碼

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null) return false;
        ListNode show = head;
        ListNode fast = head;
        if(fast.next != null) fast = fast.next.next;
        show = show.next;
        while(show != null && fast != null){
            if(show == fast) return true;
            show = show.next;
            if(fast.next == null) return false;
            fast = fast.next.next;
        }
        return false;
    }
}