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.
1public class ListNode {
2 public int val;
3 public ListNode next;
4 public ListNode(int val = 0, ListNode next = null) {
5 this.val = val;
6 this.next = next;
7 }
8}
9
10public class Solution {
11 public int GetLength(ListNode head) {
12 int length = 0;
13 while (head != null) {
14 length++;
15 head = head.next;
16 }
17 return length;
18 }
19
20 public ListNode RemoveNthFromEnd(ListNode head, int n) {
21 int length = GetLength(head);
22 ListNode dummy = new ListNode(0, head);
23 ListNode current = dummy;
24 for (int i = 0; i < length - n; i++) {
25 current = current.next;
26 }
27 current.next = current.next.next;
28 return dummy.next;
29 }
30}
The C# code provided effectively mirrors solutions in other languages with a two-pass algorithm. It utilizes an additional helper function to calculate the length of the list and a dummy node for simplifying the removal of nodes.
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 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6class Solution:
7 def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
8 dummy = ListNode(0, head)
9 fast = slow = dummy
10 for _ in range(n + 1):
11 fast = fast.next
12 while fast:
13 fast = fast.next
14 slow = slow.next
15 slow.next = slow.next.next
16 return dummy.next
In Python, the one-pass solution engages two pointers, advancing fast first by n nodes. Following this lead, fast and slow traverse concurrently, ensuring slow's position is optimal for the necessary node removal.