From 848ae453dd1ba8f63d9a23fdf135e82117aef412 Mon Sep 17 00:00:00 2001 From: PrakarshKamal Date: Sat, 28 Feb 2026 14:44:18 -0500 Subject: [PATCH] Complete Linked-List-1 --- LinkedListCycleII.java | 45 ++++++++++++++++++++++++++++++++++++++++++ RemoveNthNode.java | 26 ++++++++++++++++++++++++ ReverseLinkedList.java | 26 ++++++++++++++++++++++++ 3 files changed, 97 insertions(+) create mode 100644 LinkedListCycleII.java create mode 100644 RemoveNthNode.java create mode 100644 ReverseLinkedList.java diff --git a/LinkedListCycleII.java b/LinkedListCycleII.java new file mode 100644 index 00000000..aae9eaa5 --- /dev/null +++ b/LinkedListCycleII.java @@ -0,0 +1,45 @@ +// Brute force O(n) time, O(n) space +// public class Solution { +// public boolean detectCycle(ListNode head) { +// Set set = new HashSet<>(); + +// while (head != null) { +// if (set.contains(head)) { +// return head; +// } +// set.add(head); +// head = head.next; +// } +// return null; +// } +// } + +// Slow and fast O(n) time, O(1) space +class Solution { + public ListNode detectCycle(ListNode head) { + ListNode slow = head; + ListNode fast = head; + boolean hasCycle = false; + + // fast != null needed for even length, fast.next != null needed for odd length + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + + if (slow == fast) { + hasCycle = true; + break; + } + } + + if (!hasCycle) return null; + + slow = head; + + while (slow != fast) { + slow = slow.next; + fast = fast.next; + } + return slow; + } +} diff --git a/RemoveNthNode.java b/RemoveNthNode.java new file mode 100644 index 00000000..023944b9 --- /dev/null +++ b/RemoveNthNode.java @@ -0,0 +1,26 @@ +// Two pointers O(n) time, O(1) space +class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode dummy = new ListNode(-1); + dummy.next = head; + + ListNode slow = dummy; + ListNode fast = dummy; + + int count = 0; + while (count <= n) { + fast = fast.next; + count++; + } + // after loop we have difference of n between slow and fast + + while (fast != null) { + slow = slow.next; + fast = fast.next; + } + slow.next = slow.next.next; // deleting by skipping node and reassigning to node after + + return dummy.next; // return head which is node to remove + } +} + diff --git a/ReverseLinkedList.java b/ReverseLinkedList.java new file mode 100644 index 00000000..aac91198 --- /dev/null +++ b/ReverseLinkedList.java @@ -0,0 +1,26 @@ +// O(n) time, O(1) space +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) return head; + + ListNode prev = null; + ListNode curr = head; + + while (curr != null) { + ListNode temp = curr.next; + curr.next = prev; + prev = curr; + curr = temp; + } + return prev; + } +} + +class ListNode { + int val; + ListNode next; + ListNode() {} + ListNode(int val) { this.val = val; } + ListNode(int val, ListNode next) { this.val = val; this.next = next; } +} + \ No newline at end of file