When it is required to display the nodes of a linked list in reverse without using the method of recursion, a method to add elements to the linked list, and a method to display the elements in reverse order is defined.
Below is a demonstration for the same −
Example
class Node: def __init__(self, data): self.data = data self.next = None class my_linked_list: def __init__(self): self.head = None self.last_node = None def add_value(self, my_data): if self.last_node is None: self.head = Node(my_data) self.last_node = self.head else: self.last_node.next = Node(my_data) self.last_node = self.last_node.next def reverse_display(self): end_node = None while end_node != self.head: curr = self.head while curr.next != end_node: curr = curr.next print(curr.data) end_node = curr my_instance = my_linked_list() n = int(input('How many elements you wish to add ? ')) for i in range(n): data = int(input('Enter a data item : ')) my_instance.add_value(data) print('The reversed linked list is : ') my_instance.reverse_display()
Output
How many elements you wish to add ? 5 Enter a data item : 43 Enter a data item : 67 Enter a data item : 87 Enter a data item : 12 Enter a data item : 34 The reversed linked list is : 34 12 87 67 43
Explanation
The ‘Node’ class is created.
Another ‘my_linked_list’ class with required attributes is created.
It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’ and last node to ‘None’.
Another method named ‘add_value’ is defined, that is used to add data to the linked list.
Another method named ‘reverse_display’ is defined that is used to display the linked list data in reverse order on the console.
An object of the ‘my_linked_list’ class is created.
The user input is taken for the number of elements in the linked list.
This range is iterated over, and the methods are called on it to add data.
The elements are reversed using ‘reverse_display’ and displayed on the console.