from itertools import count
from logging import exception
class Node: #ele in linked list call node,node will have data, and pointer to next
#so create node cls with data and next
def __init__(self,data):
self.data=data
self.next=None
#start of linked list called head
class Linkedlist:
def __init__(self):
self.head=None
def addinfront(self,newdata):
# to add node in front of linked list, create new node that you wanted to add
# point that to already existing linked list head
# now make new node as head of linked list
node=Node(newdata)
node.next=self.head
self.head=node
#to print the linked list, head node of linked list assign to variable
# if variable is not none it iterate using while loop
# prints data and next node is assign to varible
def insertinend(self,newdata):
# to add at end we have to check weather linked list is none or not
#if it is none head node will be new node
#else iterate throuth each node find next to node is none
newnode=Node(newdata)
if self.head is None:
self.head=newnode
return
else:
last=self.head
while last.next:
last=last.next
last.next=newnode
def insertlist(self,newlist):
#self.head=None
for date in newlist:
self.insertinend(date)
def length(self):
count=0
temp=self.head
while temp:
count+=1
temp=temp.next
return count
def remove_ele_index(self,index):
if index<0 or index>=self.length():
raise exception("Invalid index")
if index==0:
self.head=self.head.next
count=0
temp=self.head
while temp:
if count==index-1:
temp.next=temp.next.next
break
count+=1
temp=temp.next
def Afterpreviousnode(self,previousnode,newdata):
if previousnode is None:
print("Enter the valid Node")
else:
newnode=Node(newdata)
newnode.next=previousnode.next
previousnode.next=newnode
def insert_at(self,index,newdata):
if index<0 or index>=self.length():
raise exception("Invalid index")
if index==0:
self.addinfront(newdata)
return
count=0
temp=self.head
while temp:
if count==index-1:
newnode=Node(newdata)
newnode.next=temp.next.next
temp.next=newnode
break
count+=1
temp=temp.next
def print(self):
temp=self.head
while temp:
print(temp.data,end=" ")
temp=temp.next
if __name__=="__main__":
llist=Linkedlist()
llist.head=Node(4)
second=Node(19)
Third=Node(8)
llist.head.next=second
second.next=Third
llist.addinfront(1)
llist.addinfront(55)
llist.addinfront(5)
llist.insertinend(99)
llist.insertlist(["apple","banana","mango"])
llist.Afterpreviousnode(Third,0)
llist.remove_ele_index(3)
llist.insert_at(3,33)
llist.insert_at(0,1000)
llist.print()
print("lenth is:",llist.length())
Comments
Post a Comment