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


When it is required to print the alternate nodes in a linked list 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. Another helper function is used that calls the previously defined method to get alternate values.

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):
      self.alternate_helper_fun(self.head)

   def alternate_helper_fun(self, curr):
      if curr is None:
         return
      print(curr.data, end = ' ')
      if curr.next:
         self.alternate_helper_fun(curr.next.next)

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 :78 56 34 52 71 96 0 80
The alternate elements in the linked list are :
78 34 71 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 used to call the helper function.

  • Another helper function, named ‘alternate_helper_fun’ is defined that is used to iterate through the linked list, and display elements in alternative indices.

  • It is a recursive function, hence it calls itself again and again.

  • This is used to call the ‘alternate_nodes’ function since recursion is being used.

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

  • The alternate_nodes method is called, to display the alternate elements.

  • This output is displayed on the console.

Updated on: 14-Apr-2021

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements