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 −


 Live Demo

class Node:
   def __init__(self, data): = data = 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: = Node(my_data)
         self.last_node =

   def print_it(self):
      curr = self.head
      while curr:
         curr =

   def alternate_nodes(self):
      curr = self.head
      while curr:
         if is not None:
            curr =

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


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


  • 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.

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