题目描述
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
分析
快慢指针,定义两个指针,一个每次走一步,另一个每次走两步。如果快指针“遇到”了慢指针,说明有环。
代码
public static boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (fast != null) {
if (fast.next == null || fast.next.next == null) {
return false;
}
if (slow == fast) {
return true;
}
fast = fast.next.next;
slow = slow.next;
}
return false;
}