From 344e25107959d5ca5ce532e55ae1015aa4440857 Mon Sep 17 00:00:00 2001 From: takudzwa Date: Sat, 28 Feb 2026 15:54:40 -0500 Subject: [PATCH] [detect cycle && remove nth && reverse list recursive] --- LinkedListCycle.java | 33 +++++++++++++++++++++++++++++++++ RemoveNth.java | 28 ++++++++++++++++++++++++++++ ReverseList.java | 19 +++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 LinkedListCycle.java create mode 100644 RemoveNth.java create mode 100644 ReverseList.java diff --git a/LinkedListCycle.java b/LinkedListCycle.java new file mode 100644 index 00000000..fe53ee37 --- /dev/null +++ b/LinkedListCycle.java @@ -0,0 +1,33 @@ +public class LinkedListCycle { + // Time Complexity : O(n) + // Space Complexity : O(1) + // Did this code successfully run on Leetcode : yes + // 2(a + b) = a + b + k(c + b) + // a = (k -1 )b + kc + // + public ListNode detectCycle(ListNode head) { + if (head == null || head.next == null ) return null; + ListNode slow = head.next; + ListNode fast = head.next.next; + + while (fast != slow) { + if(fast == null || fast.next == null) { + return null; + } + slow = slow.next; + fast = fast.next.next; + } + + if(fast == null || fast.next == null) { + return null; + } + slow = head; + while (fast != slow) { + fast = fast.next; + slow = slow.next; + } + return slow; + + + } +} \ No newline at end of file diff --git a/RemoveNth.java b/RemoveNth.java new file mode 100644 index 00000000..4d13fa76 --- /dev/null +++ b/RemoveNth.java @@ -0,0 +1,28 @@ +public class RemoveNth { + // Time Complexity : O(n) + // Space Complexity : O(1) + // Did this code successfully run on Leetcode : yes + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode dummy = new ListNode(-1); + dummy.next = head; + ListNode slow = dummy; + ListNode fast = dummy; + if(head == null || head.next == null) { + return null; + } + for(int i = 0; i <= n; i++) { + fast = fast.next; + } + + while(fast != null) { + fast = fast.next; + slow = slow.next; + } + fast = slow.next; + slow.next = slow.next.next; + + + return dummy.next; + + } +} \ No newline at end of file diff --git a/ReverseList.java b/ReverseList.java new file mode 100644 index 00000000..c93cf86a --- /dev/null +++ b/ReverseList.java @@ -0,0 +1,19 @@ +public class ReverseList { + + // Time Complexity : O(n) + // Space Complexity : O(h) + // Did this code successfully run on Leetcode : yes + public ListNode reverseList(ListNode head) { + return helper(head); + } + public ListNode helper(ListNode root) { + if (root == null || root.next == null) return root; + + ListNode head = helper(root.next); + root.next.next = root; + root.next = null; + + return head; + + } +} \ No newline at end of file