class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
print()
temp = self.head
while temp!=None:
print(temp.data, end="-->")
temp = temp.next
def InsertATNode(self,data,index):
dataADD = Node(data)
pos = 1
temp1 = self.head
temp2 = temp1.next
if index == pos:
dataADD.next = temp1
self.head = dataADD
else:
if index<=0:
print('\nEnter a valid index')
while index!=0:
index = index-1
if index == 1:
dataADD.next = temp2
temp1.next = dataADD
break
elif index > LinkedList.length(self):
print('\nSize is out of index')
break
else:
temp1 = temp1.next
temp2 = temp1.next
pos=pos+1
def length(self):
temp = self.head
count = 0
while temp!=None:
count=count+1
temp = temp.next
return count
if __name__ == "__main__":
llist = LinkedList()
first = Node(10)
second = Node(20)
third = Node(30)
fourth = Node(40)
fifth = Node(50)
llist.head = first
first.next = second
second.next = third
third.next = fourth
fourth.next = fifth
llist.display()
llist.InsertATNode(100,0)
llist.display()
No comments:
Post a Comment