/** * 题目: * 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; }
}