When it is required to find the length of a linked list without using recursion, a method to add elements to the linked list, and a method to calculate the length of the linked list 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 calculate_length(self): curr = self.head length_val = 0 while curr: length_val = length_val + 1 curr = curr.next return length_val my_instance = my_linked_list() my_data = input('Enter elements of the linked list ').split() for elem in my_data: my_instance.add_value(int(elem)) print('The length of the linked list is ' + str(my_instance.calculate_length()))
Output
Enter elements of the linked list 34 12 56 86 32 99 0 6 The length of the linked list is 8
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 ‘calculate_length’ is defined that is used to find the length of the linked list.
An object of the ‘my_linked_list’ class is created.
The user input is taken to get the elements in the linked list.
The methods are called on it to add data.
The calculate_length method is called, to find the length of the list.
This output is displayed on the console.