-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLinkedListCycle.java
More file actions
38 lines (34 loc) · 962 Bytes
/
LinkedListCycle.java
File metadata and controls
38 lines (34 loc) · 962 Bytes
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
33
34
35
36
37
38
public class LinkedListCycle {
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public static boolean hasCycle(ListNode head) {
if (head == null) return false;
ListNode p = head;
ListNode q = head.next;
while (p != null && q != null) {
if (p == q) return true;
try {
p = p.next;
q = q.next.next;
} catch (Exception e) {
return false;
}
}
return false;
}
public static void main(String[] args) {
ListNode data1 = new ListNode(1);
ListNode data2 = new ListNode(2);
data1.next = data2;
ListNode data3 = new ListNode(3);
data2.next = data3;
data3.next = null;
System.out.println(hasCycle(data1));
}
}