Nth-to-Last Node

In this lesson, we will learn how to get the Nth-to-Last Node from a given linked list.

In this lesson, we are going to find how to get the Nth-to -Last Node from a linked list. First of all, we’ll clarify what we mean by Nth-to -Last Node in the illustration below:

As you can see from the illustration above, if N equals 2, we want to get the second to last node from the linked list.

We will be using two solutions to solve this problem.

Solution 1 #

We’ll break down this solution in two simple steps:

  1. Calculate the length of the linked list.
  2. Count down from the total length until n is reached.

For example, if we have a linked list of length four, then we’ll begin from the head node and decrement the calculated length of the linked list by one as we traverse each node in the linked list. We’ll only stop on the node when our count becomes equal to n.

Implementation #

Let’s try implementing this solution in Python:

Press + to interact
def print_nth_from_last(self, n):
total_len = self.len_iterative()
cur = self.head
while cur:
if total_len == n:
print(cur.data)
return cur.data
total_len -= 1
cur = cur.next
if cur is None:
return

Explanation #

The method ...