leetcode:(141) Linked List Cycle(java)
阿新 • • 發佈:2018-11-06
/** * 題目: * Given a linked list, determine if it has a cycle in it. * 解題思路: * 通過考慮不同速度的兩個指標 - 慢速指標和快速指標,可以將空間複雜度降低到O(1)O(1)。 * 慢速指標一次移動一步,而快速指標一次移動兩步。 * 如果連結串列中沒有迴圈,則快速指標最終將到達結尾,在這種情況下我們可以返回false。 */ public class HasCycle_141_1017 { 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; } fast = fast.next.next; slow = slow.next; } return true; }
}