This approach involves two passes through the linked list to find the node that needs to be removed. In the first pass, compute the length of the list. In the second pass, remove the (Len - n + 1)th node from the start of the list by maintaining a pointer to manage node deletions properly.
Time Complexity: O(L), where L is the length of the linked list since we pass over the list twice (to calculate length and to remove the node).
Space Complexity: O(1) since no additional data structures other than few pointers are used.
1function ListNode(val, next) {
2 this.val = (val===undefined ? 0 : val);
3 this.next = (next===undefined ? null : next);
4}
5
6var getLength = function(head) {
7 let length = 0;
8 while (head !== null) {
9 length++;
10 head = head.next;
11 }
12 return length;
13};
14
15var removeNthFromEnd = function(head, n) {
16 let length = getLength(head);
17 let dummy = new ListNode(0, head);
18 let current = dummy;
19 for (let i = 0; i < length - n; i++) {
20 current = current.next;
21 }
22 current.next = current.next.next;
23 return dummy.next;
24};
The JavaScript implementation adopts the same two-step strategy. It first calculates the total node count, utilizes a dummy node to ensure seamless deletions, and removes the required element by adjusting pointers on the second pass.
This approach uses two pointers, fast and slow. Begin by moving the fast pointer n steps ahead. Then move both pointers simultaneously until fast reaches the end. This provides the correct position to remove the nth node from the end efficiently in one go.
Time Complexity: O(L), where L stands for the list's total node count.
Space Complexity: O(1), since a fixed amount of pointers are manipulated.
1class ListNode {
2 int val;
3 ListNode next;
4 ListNode() {}
5 ListNode(int val) { this.val = val; }
6 ListNode(int val, ListNode next) { this.val = val; this.next = next; }
7}
8
9class Solution {
10 public ListNode removeNthFromEnd(ListNode head, int n) {
11 ListNode dummy = new ListNode(0);
12 dummy.next = head;
13 ListNode fast = dummy;
14 ListNode slow = dummy;
15 for (int i = 0; i <= n; i++) {
16 fast = fast.next;
17 }
18 while (fast != null) {
19 fast = fast.next;
20 slow = slow.next;
21 }
22 slow.next = slow.next.next;
23 return dummy.next;
24 }
25}
This Java implementation similarly employs fast and slow pointers. Fast advances ahead by n nodes first, followed by moving both pointers concurrently. By the time fast is null, slow stands right before the needed deletion point, simplifying the removal process.