blob: a48f38af966d10de6e337a042bdf0d75da85b441 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import java.lang.*;
import java.util.*;
import node.*;
class ListCycle {
public static boolean hasCycle(ListNode head) {
if (head == null)
return false;
else if (head.next == null)
return false;
ListNode slow = head;
ListNode fast = head.next;
while (slow != null && fast.next != null) {
if (slow == fast)
return true;
slow = slow.next;
fast = fast.next.next;
}
return false;
}
public static void main(String[] args) {
ListNode first = new ListNode(2, null);
ListNode third = new ListNode(4, first);
ListNode second = new ListNode(0, third);
first.next = second;
ListNode head = new ListNode(3, first);
System.out.println(hasCycle(head));
}
}
|