From 6522012065712fb0ece31bff9ff10b38a83b10e1 Mon Sep 17 00:00:00 2001 From: Michael Hunteman Date: Thu, 22 Sep 2022 10:14:04 -0500 Subject: Initial commit --- ListCycle.java | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 ListCycle.java (limited to 'ListCycle.java') 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)); + } +} -- cgit v1.2.3