public ListNode removeNthFromEnd(ListNode head, int n) {
if (head ==null)
returnnull;
//get length of list ListNode p = head;
int len = 0;
while (p !=null) {
len++;
p = p.next;
}
//if remove first nodeint fromStart = len - n + 1;
if (fromStart == 1)
return head.next;
//remove non-first node p = head;
int i = 0;
while (p !=null) {
i++;
if (i == fromStart - 1) {
p.next= p.next.next;
}
p = p.next;
}
return head;
}
Method 2 - One Pass - Using Slow and Fast Pointers#
Utilize fast and slow pointers, positioning the fast pointer n steps ahead of the slow pointer. When the fast pointer reaches the end, the slow pointer will be at the element just before the target. This method is often referred to as the frame-based solution.
We can first run the code similar to Find Nth Node From End Of Linked List, with some modifications. Firstly, we prepend the list with the dummy node, and slow pointer will point to it.
Here found is passed by reference and is updated again and again. When we reach the end of the linked list, it is set to 1, otherwise it is incremented by 1.