diff --git a/Java/Random_programs/LinkedList.java b/Java/Random_programs/LinkedList.java new file mode 100644 index 00000000..731b912f --- /dev/null +++ b/Java/Random_programs/LinkedList.java @@ -0,0 +1,68 @@ +class ListNode { + int val; + ListNode next; + + ListNode(int val) { + this.val = val; + this.next = null; + } +} + +public class LinkedList { + + public static ListNode removeNthFromEnd(ListNode head, int n) { + // Create a dummy node + ListNode dummy = new ListNode(0); + dummy.next = head; + + // Initialize two pointers + ListNode first = dummy; + ListNode second = dummy; + + // Move first pointer n+1 steps ahead + for (int i = 0; i <= n; i++) { + first = first.next; + } + + // Move both pointers until first reaches the end + while (first != null) { + first = first.next; + second = second.next; + } + + // Remove the nth node from the end + second.next = second.next.next; + + // Return the modified list + return dummy.next; + } + + // Helper function to print the linked list + public static void printList(ListNode head) { + while (head != null) { + System.out.print(head.val + " "); + head = head.next; + } + System.out.println(); + } + + public static void main(String[] args) { + // Create a linked list: 1 -> 2 -> 3 -> 4 -> 5 + ListNode head = new ListNode(1); + head.next = new ListNode(2); + head.next.next = new ListNode(3); + head.next.next.next = new ListNode(4); + head.next.next.next.next = new ListNode(5); + + // Print the original list + System.out.print("Original List: "); + printList(head); + + // Remove the 2nd node from the end (4 in this case) + head = removeNthFromEnd(head, 2); + + // Print the modified list + System.out.print("Modified List: "); + printList(head); + } +} diff --git a/Java/Random_programs/Solution.java b/Java/Random_programs/Solution.java new file mode 100644 index 00000000..1988457a --- /dev/null +++ b/Java/Random_programs/Solution.java @@ -0,0 +1,30 @@ + +class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } +} + +public class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode dummy = new ListNode(0); + dummy.next = head; + ListNode first = dummy; + ListNode second = dummy; + + // Advance first pointer so that the gap between first and second is n nodes apart + for (int i = 0; i <= n; i++) { + first = first.next; + } + + // Move first to the end, maintaining the gap + while (first != null) { + first = first.next; + second = second.next; + } + + // Remove the nth node from the end + second.next = second.next.next; + return dummy.next; + } +} \ No newline at end of file