Insertion in Linked List in DSA Python
by DataFlair Team
Program 1
# Impelmentation of Single Linked List
# class for size of Node
class Node:
def __init__(self):
self.data=None
self.add=None
class LinkedList:
def __init__(self):
self.start=None
self.count=0
#method for create list
def createList(self):
n=int(input("Enter an element"))
self.start=Node()
self.start.data=n
self.start.add=None
temp=self.start
self.count=self.count+1
ch=input("Want to continue(Y/N)")
while(ch=="Y"):
n=int(input("Enter an element"))
newnode=Node()
newnode.data=n
newnode.add=None
temp.add=newnode
temp=newnode
self.count=self.count+1
ch=input("Want to continue(Y/N)")
#method for display list
def displayList(self):
if(self.start==None):
print("List is empty")
else:
print("Elements of List: ")
temp=self.start
while(temp!=None):
print(temp.data,end=" ")
temp=temp.add
print("\nTotal Node is: ",self.count)
#method for insert node at first position
def insertFirst(self):
if(self.start==None):
print("List is empty")
else:
n=int(input("Enter an element for insert"))
newnode=Node()
newnode.data=n
newnode.add=None
newnode.add=self.start
self.start=newnode
self.count=self.count+1
#method for insert node at last position
def insertLast(self):
if(self.start==None):
print("List is empty")
else:
n=int(input("Enter an element for insert"))
newnode=Node()
newnode.data=n
newnode.add=None
temp=self.start
while(temp.add!=None):
temp=temp.add
temp.add=newnode
self.count=self.count+1
#method for insert node at middle position
def insertMiddle(self):
if(self.start==None):
print("List is empty")
else:
n=int(input("Enter an element for insert"))
newnode=Node()
newnode.data=n
newnode.add=None
pos=int(input("Enter the position"))
if(pos>self.count):
print("Invalid position")
else:
i=1
next=self.start
while(i<pos):
prev=next
next=next.add
i=i+1
prev.add=newnode
newnode.add=next
self.count=self.count+1
# Main Menu
mylist=LinkedList()
while(1):
print("\n--------------------------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()
elif(choice==3):
mylist.insertFirst()
elif(choice==4):
mylist.insertMiddle()
elif(choice==5):
mylist.insertLast()
else:
break
Tags: dsa pythondsa python practicaldsa python programdsa python program on insertion in linked listdsa using pythoninsertion in linked listinsertion in linked list in dsa python
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.