下一题 leetcode 142. Linked List Cycle II
返回是否有环
龟兔赛跑,如果有环,必然能相遇。
// 快慢指针 // Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle. //Memory Usage: 38.8 MB, less than 16.56% of Java online submissions for Linked List Cycle. public boolean hasCycle(ListNode head) { if (head == null) return false; ListNode fast = head.next; while (fast != null && fast.next != null) { if (fast == head) return true; fast = fast.next.next; head = head.next; } return false; }