Site icon DataFlair

Create and Display in Circular Linked List in DSA Python

Program 1

# Implemenation of Circular linked list 
class Node:
    def __init__(self):
         self.data=None
         self.add=None

class CircularLinkedList:
     def __init__(self):
           self.start=None
           self.count=0

           # create list
     def createList(self):
          n=int(input("Enter an element"))
          self.start=Node()
          self.start.data=n
          self.start.add=self.start
          temp=self.start
          self.count=self.count+1
          choice=input("Want to continue")
          while(choice=="Y" or choice=="y"):
                n=int(input("Enter next element"))
                newnode=Node()
                newnode.data=n
                newnode.add=self.start
                temp.add=newnode
                temp=temp.add
                self.count=self.count+1
                choice=input("Want to continue")
# Display list
     def displayList(self):
          if(self.start==None):
                print("List not found")
          else:
                temp=self.start
                while(True):
                      print(temp.data,end=" ")
                      temp=temp.add
                      if(temp==self.start):
                            break
                print("\nTotal Node is : ",self.count)   
            

# Main Method
mylist=CircularLinkedList()
while(1):
    print("\n----------------------Circular Linked List Menu--------------\n")
    print("1.Create")
    print("2.Display")
    print("3.Insert First")
    print("4.Insert Middle")
    print("5.Insert Last")
    print("6.Delete First")
    print("7.Delete Middle")
    print("8.Delete Last")
    print("9.Exit")
    print("\n------------------------------------------------------------\n")
    choice=int(input("Enter your choice"))
    if(choice==1):
          mylist.createList()
    elif(choice==2):
          mylist.displayList()      
    else:
         break

 

Exit mobile version