From e0991e08c12869e71bcdde512ed11c29d8d74624 Mon Sep 17 00:00:00 2001 From: Hriday-A Date: Mon, 4 May 2026 15:46:22 -0500 Subject: [PATCH] Linked-List-1 --- LL_cycle_II.java | 25 +++++++++++++++++++++++++ remove_nth_node.java | 25 +++++++++++++++++++++++++ reverse_ll.java | 18 ++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 LL_cycle_II.java create mode 100644 remove_nth_node.java create mode 100644 reverse_ll.java diff --git a/LL_cycle_II.java b/LL_cycle_II.java new file mode 100644 index 00000000..72700255 --- /dev/null +++ b/LL_cycle_II.java @@ -0,0 +1,25 @@ +// Time Complexity : O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : yes +public class LL_cycle_II { + public ListNode detectCycle(ListNode head) { + ListNode slow = head; + ListNode fast = head; + boolean flag = false; + while(fast!=null && fast.next!=null){ + slow = slow.next; + fast=fast.next.next; + if(slow==fast){ + flag = true; + break; + } + } + fast = head; + if(!flag) return null; + while(slow!=fast){ + slow=slow.next; + fast=fast.next; + } + return slow; + } +} diff --git a/remove_nth_node.java b/remove_nth_node.java new file mode 100644 index 00000000..b64175b7 --- /dev/null +++ b/remove_nth_node.java @@ -0,0 +1,25 @@ +// Time Complexity : O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode :yes +class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode dummy = new ListNode(-1); + dummy.next = head; + ListNode slow= dummy; + ListNode fast = dummy; + int cnt=0; + while(cnt<=n){ + fast = fast.next; + cnt++; + } + while(fast!=null){ + slow=slow.next; + fast=fast.next; + } + ListNode temp = slow.next; + slow.next = slow.next.next; + temp.next = null; + return dummy.next; // head is no longer the orginal head if it was deleted + + } +} \ No newline at end of file diff --git a/reverse_ll.java b/reverse_ll.java new file mode 100644 index 00000000..1802a987 --- /dev/null +++ b/reverse_ll.java @@ -0,0 +1,18 @@ +// Time Complexity : O(n) +// Space Complexity :O(1) +// Did this code successfully run on Leetcode : yes +// we use 3 pointers to reverse the list by storing the values with which we loose connection +class Solution { + public ListNode reverseList(ListNode head) { + ListNode curr = head; + ListNode prev = null; + while( curr!= null){ + ListNode temp = curr.next; + curr.next = prev; + prev = curr; + curr = temp; + // System.out.println(curr); + } + return prev; + } +} \ No newline at end of file