Nth-to-Last Node
In this lesson, we will learn how to get the Nth-to-Last Node from a given linked list.
We'll cover the following...
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:
- Calculate the length of the linked list.
- 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:
def print_nth_from_last(self, n):total_len = self.len_iterative()cur = self.headwhile cur:if total_len == n:print(cur.data)return cur.datatotal_len -= 1cur = cur.nextif cur is None:return
Explanation #
The method ...