# 19 Remove Nth Node From End of List

19 Remove Nth Node From End of List

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

For 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.
* Try to do this in one pass.
* This is a two pass algorithm O(2n) - as I have use the first pass to find the size of the linked list. Since n is reletive to the end, I the front of the linked list n is not known for me.

```cpp
ListNode* removeNthFromEnd(ListNode* head, int n) {
    // head is null
    if (!head) return head;

    ListNode *current = head;
    ListNode *prev = nullptr;

    // iterate to find size of LL
    int size = 0;
    int count = 0;

    while (current != nullptr) {
        size++;
        current = current->next;
    }    

    current = head;

    // size is one 
    if (size == 1) {
        delete head;
        return nullptr;
    }
    // n is end
    else if (n == 1) {
        // iterate to end
        while (current->next != nullptr) {
            prev = current;
            current = current->next;
        }    
        prev->next = nullptr;
        delete current;
        return head;
    }

    // n is front 
    else if (n == size) {
        head = current->next;
        delete current;
        return head;
    }
    // n is front or in the middle
    else {
        // iterate to n
        while (current != nullptr && count < size - n) {
            prev = current;
            current = current->next;
            count++;
        }    
        prev->next = current->next;
        delete current;
    }

    return head;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/19_remove_nth_node_from_end_of_list.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
