Python Program to Print the Alternate Nodes in a Linked List without using Recursion

PythonServer Side ProgrammingProgramming

When it is required to print the alternate nodes in a linked list without using recursion, a method to add elements to the linked list, a method to display the elements of the linked list, and a method to get the alternate values of a linked list are defined.

Below is a demonstration for the same −

Example

 Live Demo

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 print_it(self):
      curr = self.head
      while curr:
         print(curr.data)
         curr = curr.next

   def alternate_nodes(self):
      curr = self.head
      while curr:
         print(curr.data)
         if curr.next is not None:
            curr = curr.next.next
         else:
            break

my_instance = my_linked_list()
my_list = input("Enter the elements of the linked list :").split()
for elem in my_list:
   my_instance.add_value(elem)
print("The alternate elements in the linked list are :")
my_instance.alternate_nodes()

Output

Enter the elements of the linked list :56 78 43 51 23 89 0 6
The alternate elements in the linked list are :
56
43
23
0

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 ‘print_it’ is defined, that iterates over the list, and prints the elements.

  • Another method named ‘alternate_nodes’ is defined that is defined that is used to iterate through the linked list.

  • An object of the ‘my_linked_list’ class is created.

  • The alternate_nodes method is called, to find the elements in alternative indices.

  • This output is displayed on the console.

raja
Published on 14-Apr-2021 13:18:11
Advertisements