diff --git a/LinkedListCycleII.java b/LinkedListCycleII.java new file mode 100644 index 00000000..e89fdc62 --- /dev/null +++ b/LinkedListCycleII.java @@ -0,0 +1,37 @@ +// Time Complexity : O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : yes + +// Use slow and fast pointers to detect whether a cycle exists. +// If no cycle is found, return null. +// Reset one pointer to the head and move both one step at a time until they meet at the cycle's starting node. + +public class LinkedListCycleII { + public ListNode detectCycle(ListNode head) { + ListNode slow = head, fast = head; + boolean isCycleExists = false; + + while(fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + + if(slow == fast) { + isCycleExists = true; + break; + } + } + + if(!isCycleExists) { + return null; + } + + slow = head; + + while(slow != fast) { + slow = slow.next; + fast = fast.next; + } + + return fast; + } +} \ No newline at end of file diff --git a/RemoveNthNode.java b/RemoveNthNode.java new file mode 100644 index 00000000..5fb484ad --- /dev/null +++ b/RemoveNthNode.java @@ -0,0 +1,35 @@ +// Time Complexity : O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes + +// Find the length of the linked list using a dummy node. +// Compute the position of the node to remove and traverse to its previous node. +// Skip the target node by updating the previous node's next pointer. + +class RemoveNthNode { + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode dummyHead = new ListNode(-1, head); + + ListNode current = dummyHead; + int length = 0; + + while(current != null) { + length++; + current = current.next; + } + + int targetIndex = length - n + 1; + int index = 1; + current = dummyHead; + while(index < targetIndex - 1) { + current = current.next; + index++; + } + current.next = current.next.next; + if(index == 1) { + head = current.next; + } + + return head; + } +} \ No newline at end of file diff --git a/ReverseLinkedList.java b/ReverseLinkedList.java new file mode 100644 index 00000000..2e84d223 --- /dev/null +++ b/ReverseLinkedList.java @@ -0,0 +1,22 @@ +// Time Complexity : O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes + +// Traverse the linked list while maintaining previous, current, and next pointers. +// Reverse each node's next pointer to point to the previous node. +// Move the pointers forward and return the new head after the traversal completes. + +class ReverseLinkedList { + public ListNode reverseList(ListNode head) { + ListNode prev = null, current = head; + + while(current != null) { + ListNode next = current.next; + current.next = prev; + prev = current; + current = next; + } + + return prev; + } +} \ No newline at end of file