|  | 
|  | 1 | +#Represents the node of list.     | 
|  | 2 | +class Node:     | 
|  | 3 | +  def __init__(self,data):     | 
|  | 4 | +    self.data = data;     | 
|  | 5 | +    self.next = None;     | 
|  | 6 | +      | 
|  | 7 | +class CreateList:     | 
|  | 8 | +  #Declaring head and tail pointer as null.     | 
|  | 9 | +  def __init__(self):     | 
|  | 10 | +    self.head = Node(None);     | 
|  | 11 | +    self.tail = Node(None);     | 
|  | 12 | +    self.head.next = self.tail;     | 
|  | 13 | +    self.tail.next = self.head;     | 
|  | 14 | +         | 
|  | 15 | +  #This function will add the new node at the end of the list.     | 
|  | 16 | +  def add(self,data):     | 
|  | 17 | +    newNode = Node(data);     | 
|  | 18 | +    #Checks if the list is empty.     | 
|  | 19 | +    if self.head.data is None:     | 
|  | 20 | +      #If list is empty, both head and tail would point to new node.     | 
|  | 21 | +      self.head = newNode;     | 
|  | 22 | +      self.tail = newNode;     | 
|  | 23 | +      newNode.next = self.head;     | 
|  | 24 | +    else:     | 
|  | 25 | +      #tail will point to new node.     | 
|  | 26 | +      self.tail.next = newNode;     | 
|  | 27 | +      #New node will become new tail.     | 
|  | 28 | +      self.tail = newNode;     | 
|  | 29 | +      #Since, it is circular linked list tail will point to head.     | 
|  | 30 | +      self.tail.next = self.head;     | 
|  | 31 | +      | 
|  | 32 | +  #Displays all the nodes in the list     | 
|  | 33 | +  def display(self):     | 
|  | 34 | +    current = self.head;     | 
|  | 35 | +    if self.head is None:     | 
|  | 36 | +      print("List is empty");     | 
|  | 37 | +      return;     | 
|  | 38 | +    else:     | 
|  | 39 | +        print("Nodes of the circular linked list: ");     | 
|  | 40 | +        #Prints each node by incrementing pointer.     | 
|  | 41 | +        print(current.data),     | 
|  | 42 | +        while(current.next != self.head):     | 
|  | 43 | +            current = current.next;     | 
|  | 44 | +            print(current.data),     | 
|  | 45 | +      | 
|  | 46 | +      | 
|  | 47 | +class CircularLinkedList:     | 
|  | 48 | +  cl = CreateList();     | 
|  | 49 | +  #Adds data to the list     | 
|  | 50 | +  cl.add(1);     | 
|  | 51 | +  cl.add(2);     | 
|  | 52 | +  cl.add(3);     | 
|  | 53 | +  cl.add(4);     | 
|  | 54 | +  #Displays all the nodes present in the list     | 
|  | 55 | +  cl.display();     | 
0 commit comments