141.Linked List Cycle

Solution 1: accepted

The use of dummy is optional. If we do fast = head, we need to verify that head != null.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public boolean hasCycle(ListNode head) {
ListNode dummy = new ListNode(1);
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}