Remove Nth Node From End of List

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

class Solution {
    public int length(ListNode node) {
        int len = 0;
        while (node != null) {
            len++;
            node = node.next;
        }
        return len;
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null)
            return null;
        int len = length(head);
        int indexToRemove = len - n, index = 0;
        if (indexToRemove == 0)
            return head.next;
        ListNode temp = head;
        while (temp != null) {
            if (index + 1 == indexToRemove) {
                temp.next = temp.next.next;
                break;
            }
            temp = temp.next;
            index++;
        }
        return head;
    }
}

Last updated