Program:
class node:def __init__(self,data=None):
self.data=data
self.next=None
class linked_list:
def __init__(self):
self.head=node()
# Adds new node containing 'data' to the end of the linked list.
def append(self,data):
new_node=node(data)
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=new_node
print("\n\t--->>>",data,"is successfully added in the Node")
main_menu()
# Returns the length (integer) of the linked list.
def length(self):
cur=self.head
total=0
while cur.next!=None:
total+=1
cur=cur.next
return total
# Prints out the linked list in traditional Python list format.
def display(self):
elems=[]
cur_node=self.head
while cur_node.next!=None:
cur_node=cur_node.next
elems.append(cur_node.data)
print("\n\t--->>> Linked List-",elems,"\n")
main_menu()
# Returns the value of the node at 'index'.
def get(self,index):
if index>=self.length() or index<0: # added 'index<0' post-video
print("ERROR: 'Get' Index out of range!")
return None
cur_idx=0
cur_node=self.head
while True:
cur_node=cur_node.next
if cur_idx==index: return cur_node.data
cur_idx+=1
# Deletes the node at index 'index'.
def erase(self,index):
if index>=self.length() or index<0: # added 'index<0' post-video
print("ERROR: 'Erase' Index out of range!")
return
cur_idx=0
cur_node=self.head
while True:
last_node=cur_node
cur_node=cur_node.next
if cur_idx==index:
last_node.next=cur_node.next
return
cur_idx+=1
#object
L_list=linked_list()
def main_menu():
print("\n************MAIN MENU***************")
print("1. Add a new Node\n2. Display Link List")
print("3. Display the SIZE of list")
print("4. Value of Node at Index?:")
print("5. Delete the Node of Index?:\n6. Exit")
opt=int(input("\tEnter Your Option:"))
if(opt==1):
n=int(input("Enter the data in the Node:"))
#for number input str()->>int()
L_list.append(n)
elif(opt==2):
L_list.display()
elif(opt==3):
l=L_list.length()
print("\n\t--->>> The Size of the Linked list is",l,"\n")
main_menu()
elif(opt==4):
m=int(input("\tEnter the index: "))
x=L_list.get(m)
print("\n\t--->>>Value at Index",m," is ",x)
main_menu()
elif(opt==5):
n=int(input("\tEnter the index: "))
L_list.erase(n)
print("\n\t--->>The node at Index ",n," is Deleted. ")
L_list.display()
main_menu()
elif(opt==6):
exit
else:
print("\n\t--->>>InValid Option\n")
main_menu()
main_menu()
0 Comments
Post a Comment