1. 程式人生 > >【LeetCode】141. 環形連結串列(Linked List Cycle)

【LeetCode】141. 環形連結串列(Linked List Cycle)

英文練習 | 中文練習

題目描述: 給定一個連結串列,判斷連結串列中是否有環。

解題思路: 一種方法可以使用 Hash Table ,判斷該結點之前是否遇到過;更優的方法是使用雙指標,一個指標每次移動一個結點,一個指標每次移動兩個結點,如果存在環,那麼這兩個指標一定會相遇。

public boolean hasCycle(ListNode head) {
    if (head == null || head.next == null) {
        return false;
    }
    ListNode slow = head;
    ListNode fast =
head.next; while (slow != fast) { if (fast == null || fast.next == null) { return false; } slow = slow.next; fast = fast.next.next; } return true; }