Python Circular Linked List Program

PythonServer Side ProgrammingProgramming

When it is required to create a Python program that generates a linked list, a 'Node' class needs to be created. To display the data elements in the circular list, another method can be defined, that would display the data. In this class, there are two attributes, the data that is present in the node, and the access to the next node of the linked list. In a circular linked list, the head and the rear are adjacent to each other. They are connected to form a circle, and don't have 'NULL' value in the last node.

Another 'linked_list' class needs to be created that would have an initialization function, and the head of the node would be initialized to 'None'. 

Below is a demonstration for the same −

Example

Live Demo

class Node:
   def __init__(self, my_data):
      self.data = my_data
      self.next = None

class circularLinkedList:  
   def __init__(self):
      self.head = None
   def add_data(self, my_data):
      ptr_1 = Node(my_data)
      temp = self.head    
      ptr_1.next = self.head

      if self.head is not None:
         while(temp.next != self.head):
            temp = temp.next
         temp.next = ptr_1
      else:
         ptr_1.next = ptr_1
      self.head = ptr_1

   def print_it(self):
      temp = self.head
      if self.head is not None:
         while(True):
            print("%d" %(temp.data)),
            temp = temp.next
            if (temp == self.head):
               break
my_list = circularLinkedList()
print("Elements are added to the list ")
my_list.add_data (56)
my_list.add_data (78)
my_list.add_data (12)
print("The data is : ")
my_list.print_it()

Output

Elements are added to the list
The data is :
12
78
56

Explanation

  • The 'Node' class is created.
  • Another 'circularLinkedList' 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'.
  • Another method named 'add_data' is defined, that is used to add data to the circular linked list.
  • Another method named 'print_it' is defined that is used to display the linked list data on the console.
  • An object of the 'linked_list' class is created, and the methods are called on it to add data.
  • This is displayed on the console using the 'print_it' method.
raja
Published on 13-Mar-2021 10:17:10
Advertisements