Circular Linked List in DSA Python
by DataFlair Team
Program 1
# Circular Linked list
import os
class Node:
def __init__(self):
self.data=None
self.add=None
class CircularLinkedList:
def __init__(self):
self.start=None
self.count=0
def create(self):
n=int(input("Enter First element : "))
self.start=Node()
self.start.data=n
self.start.add=None
temp=self.start
self.count=self.count+1
choice=input("Want to continue(y/Y): ")
while(choice=='y' or choice=='Y'):
self.count=self.count+1
n=int(input("Enter next element : "))
newnode=Node()
newnode.data=n
newnode.add=None
temp.add=newnode
newnode.add=self.start
temp=temp.add
choice=input("Want to continue(y/Y): ")
def display(self):
if(self.start==None):
print("List is Empty")
else:
temp=self.start
while(True):
print(temp.data,end="---->")
temp=temp.add
if(temp==self.start):
break
print("\nTotal node is: ",self.count)
def insertFirst(self):
if(self.start==None):
print("List is Empty")
else:
n=int(input("Enter next element : "))
newnode=Node()
newnode.data=n
newnode.add=None
last=self.start
while(last.add!=self.start):
last=last.add
newnode.add=self.start
self.start=newnode
last.add=self.start
def insertLast(self):
if(self.start==None):
print("List is Empty")
else:
n=int(input("Enter next element : "))
newnode=Node()
newnode.data=n
newnode.add=None
last=self.start
while(last.add!=self.start):
last=last.add
last.add=newnode
newnode.add=self.start
def insertMiddle(self):
if(self.start==None):
print("List is empty")
else:
self.count=self.count+1
n=int(input("Enter an element for insert: "))
newnode=Node()
newnode.data=n
pos=int(input("Enter node position for insert: "))
i=1
next=self.start
while(i<pos):
prev=next
next=next.add
i=i+1
prev.add=newnode
newnode.add=next
# Main
os.system('cls')
mylist=CircularLinkedList()
while(1):
print("\n --------------------Linked List------------------------")
print("1. Create")
print("2. Display")
print("3. Insert First")
print("4. Insert Middle")
print("5. Insert Last")
print("6. Exit")
print("-----------------------------------------------------------")
choice=int(input("Enter your choice: "))
if(choice==1):
mylist.create()
elif(choice==2):
mylist.display()
elif(choice==3):
mylist.insertFirst()
elif(choice==4):
mylist.insertMiddle()
elif(choice==5):
mylist.insertLast()
else:
break
Tags: Circular Linked Listcircular linked list in dsa pythoncircular linked list in dsa using pythondsa pythondsa python circular linked listdsa python practicaldsa python programdsa python program on circular linked list
DataFlair Team
DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.