Linked Lists — Remove Nth Node from End of List

nathan brickett
3 min readSep 13, 2020

Back with another linked list problem today.

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.

For this problem we will be using a dummy node. This is a node that does not hold any value, but is in the list to provide an extra node at the front of the list. The purpose of the dummy node is to reduce or remove special edge cases that we may occur. These include a list that is empty, has only one node, or removing the first node. The dummy node has a value of null, but a next set equal to the head of the linked list we are working with.

First we will begin by moving the fast pointer ahead by N nodes.

Next, we keep moving until the fast pointer .next is equal to null. This ensures that our slow pointer stops right before the target node we want to remove.

In this case, we want to remove node 4. We stopped it right before the slow pointer lands on our target node.

We just have to rewire the slow pointer .next to bypass node 4 and point it to node 5.

We finish the problem by return dummyHead.next. This is the original head.

--

--