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



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 class LinkedList_structure:    def __init__(self):       self.head = None       self.last_node = None    def add_vals(self, data):       if self.last_node is None:          self.head = Node(data)          self.last_node = self.head       else:          self.last_node.next = Node(data)          self.last_node = self.last_node.next def list_length(my_list):    my_len = 0    curr = my_list.head    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)    curr = my_list.head    for i in range(l - n):       curr = curr.next    return curr.data my_instance = LinkedList_structure() my_list = input('Enter the elements of the linked list..').split() for elem in my_list:    my_instance.add_vals(int(elem)) 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.

Updated on: 2021-04-14T14:11:01+05:30

315 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements