141. Linked List Cycle
快慢指针,当快指针和慢指针重叠时说明有cycle,while条件是为了没有cycle的时候跳出循环。
public boolean hasCycle(ListNode head) {
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) { // in case that no cycle in the linked list
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}