From 7d82cdd1aa03bcfba3298cc3d2400a302487ed82 Mon Sep 17 00:00:00 2001 From: yukthi96 <63551946+yukthi96@users.noreply.github.com> Date: Fri, 20 Oct 2023 16:13:02 +0530 Subject: [PATCH] Create UniqueFloydAlgorithmpo.java --- .../UniqueFloydAlgorithmpo.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Dynamic_Programming/UniqueFloydAlgorithmpo.java diff --git a/Dynamic_Programming/UniqueFloydAlgorithmpo.java b/Dynamic_Programming/UniqueFloydAlgorithmpo.java new file mode 100644 index 0000000..9b09041 --- /dev/null +++ b/Dynamic_Programming/UniqueFloydAlgorithmpo.java @@ -0,0 +1,43 @@ + +public class UniqueFloydAlgorithm { + + public static void main(String[] args) { + ListNode head = new ListNode(3); + head.next = new ListNode(2); + head.next.next = new ListNode(0); + head.next.next.next = new ListNode(-4); + // Create cycle + head.next.next.next.next = head.next; + boolean hasCycle = hasCycle(head); + if (hasCycle) { + System.out.println("The linked list has a cycle."); + } else { + System.out.println("The linked list does not have a cycle."); + } + } + + public static boolean hasCycle(ListNode head) { + if (head == null || head.next == null) { + return false; + } + ListNode slow = head; + ListNode fast = head.next; + while (slow != fast) { + if (fast == null || fast.next == null) { + return false; + } + slow = slow.next; + fast = fast.next.next; + } + return true; + } +} +class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + next = null; + } +}