Python Program to Print Nth Node from the last of a Linked List

PythonServer Side ProgrammingProgramming

When it is required to print the specific node from the end of a linked list, the methods ‘list_length’ and ‘return_from_end’ methods are defined. The ‘list_length’ reutrns the length of the linked list.

The ‘return_from_end’ method is used to return the nth element from the end of the linked list.

Below is a demonstration for the same −

Example

Live Demo

class Node:
def __init__(self, data):
self.data = data
self.next = None

def __init__(self):
self.last_node = None

if self.last_node is None:
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def list_length(my_list):
my_len = 0
while curr:
curr = curr.next
my_len = my_len + 1
return my_len

def return_from_end(my_list, n):
l = list_length(my_list)
for i in range(l - n):
curr = curr.next
return curr.data

my_list = input('Enter the elements of the linked list..').split()
for elem in my_list:

n = int(input('Enter the value for n.. '))
my_result = return_from_end(my_instance, n)

print('The nth element from the end is: {}'.format(my_result))

Output

Enter the elements of the linked list..45 31 20 87 4
Enter the value for n.. 2
The nth element from the end is: 87

Explanation

• The ‘Node’ class is created.

• Another ‘LinkedList_structure’ class with required attributes is created.

• It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ and ‘last_node’ to ‘None’.

• A method named ‘add_vals’ is defined, that helps add a value to the stack.

• A method named ‘list_length’ is defined, that determines the length of the linked list, and returns it as output.

• Another method named ‘return_from_end’ is defined, that helps return ‘n’ values from the end of the linked list.

• An instance of the ‘LinkedList_structure’ is created.

• Elements are added to the linked list.

• The elements are displayed on the console.

• The ‘return_from_end’ method is called on this linked list.

• The output is displayed on the console.

Published on 14-Apr-2021 14:10:08