# Remove Nth Node From End of List

Similar to \[k-th element to last of a LinkedList]\({% post\_url 2016-09-07-cci-2-2 %})

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.

{% tabs %}
{% tab title="Scala" %}

```scala
trait Node {
  def value: Int
  def next: Node
}

object Empty extends Node {
  def value: Int = throw new Error("access empty variable")
  def next: Node = throw new Error("access empty variable")
}

class NonEmpty(var value: Int, var next: Node = Empty) extends Node

def toLinkedList(lst: List[Int]): Node = {
  if (lst.isEmpty) Empty
  else new NonEmpty(lst.head, toLinkedList(lst.tail))
}

def printLinkedList(head: Node): Unit = head match {
  case Empty =>
  case node: NonEmpty => {
    println(node.value)
    printLinkedList(node.next)
  }
}

/**
  * @param head
  * @param k
  * @return
  */
def removeNthElement(head: Node, k: Int):Node = head match {
  case Empty => head
  case node: NonEmpty =>
    if (node.next == Empty) Empty
    else {
      var prev: Node = Empty
      var slow: Node = head
      var fast: Node = head.next
      for (i <- 0 until k - 1 if fast != Empty) {
        fast = fast.next
      }
      while (fast != Empty) {
        prev = slow
        slow = slow.next
        fast = fast.next
      }
      prev match {
        case Empty => slow.next
        case p:NonEmpty => {
          if (p.next != Empty)
            p.next = p.next.next
          head
        }
      }
    }
}

val node = removeNthElement(toLinkedList(List(1,2,3)), 2)
printLinkedList(node)
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}


---

# 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://blog.bernardw.com/problems/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.
