aboutsummaryrefslogtreecommitdiff
path: root/ListCycle.java
diff options
context:
space:
mode:
authorMichael Hunteman <michael@michaelted.xyz>2022-09-22 10:14:04 -0500
committerMichael Hunteman <michael@michaelted.xyz>2022-09-22 10:14:04 -0500
commit6522012065712fb0ece31bff9ff10b38a83b10e1 (patch)
tree743f3c13d08be9f60bad57b74e7a1fe7cc675e89 /ListCycle.java
Initial commit
Diffstat (limited to 'ListCycle.java')
-rw-r--r--ListCycle.java32
1 files changed, 32 insertions, 0 deletions
diff --git a/ListCycle.java b/ListCycle.java
new file mode 100644
index 0000000..a48f38a
--- /dev/null
+++ b/ListCycle.java
@@ -0,0 +1,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));
+ }
+}