141. Linked List Cycle
经典的套环问题,后面的套环题变式都是用Array的index来代表pointer以此判断是否重复element之类的。。
快慢指针相遇。
time: O(n)
space: O(1)
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) return false;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
}

浙公网安备 33010602011771号