Write a program in python to perfrom following function on Singly Linked List 1) Create Singly Linked List 2) Add node 3)Display 4)Delete node 5)Find data in Singly Linked List

Singly Linked List

class node:
    //To initialize values def __init__(self,data=None): self.data=data self.next=None class linking:

    //To create Linked List def __init__(self): n=int(input('Enter how many nodes:')) for i in range(1,n+1): if i==1: self.head = node(input(f"Enter {i} data: ")) else: newnode = node(input(f"Enter {i} data: ")) cur = self.head while cur.next != None: cur = cur.next cur.next = newnode      //To add node at specific position in Linked List
def add(self,data): pos=int(input("Enter position: ")) cur = self.head c = 1 while cur.next != None: cur = cur.next c = c + 1 if pos==c: newnode = node(data) cur = self.head while cur.next != None: cur = cur.next cur.next = newnode if pos==1: cur=self.head newnode = node(data) newnode.next=cur self.head=newnode else: cn=1 cur=self.head mur=cur.next newnode = node(data) while cur.next!=None: if pos-1==cn: cur.next=newnode newnode.next=mur cur=cur.next mur=cur.next cn+=1
    //To display elements in Linked List
def display(self): cur=self.head while cur.next!=None: print(cur.data,end=" ") cur=cur.next print(cur.data,end=" ")
     //To remove a node from a specific position in Linked List
def remove(self,pos): cur = self.head c = 1 while cur.next != None: cur = cur.next c = c + 1 if pos==1: mur=self.head mur=mur.next self.head=mur if pos==c: cur = self.head mur=cur.next while mur.next!=None: cur=mur mur=cur.next cur.next=None else: cur=self.head mur=cur.next c = 1 while cur.next != None: if pos-1==c: cur.next=mur.next cur = cur.next mur = cur.next c = c + 1
    //To Find data in Linked List

    def find(self,data): cur=self.head f=0 index=1 while cur.next!=None: if int(cur.data)==data: f=1 break cur=cur.next index+=1 if int(cur.data) == data: f = 1 if f==1: print(f"Your Data Found at {index}") else: print("Your Data Not Found!!!!")
//To create menu
while True: choose = (int(input("\n1)create\n2)Add node\n3)Display\n4)Delete node\n5)Find\n6)Exit.\nEnter your choice:"))) if choose == 1: mylist = linking() if choose==2: mylist.add(input("Enter Data:")) if choose==3: mylist.display() if choose==4: mylist.remove(int(input("Enter Position:"))) if choose==5: data=int(input("Enter Data: ")) mylist.find(data) if choose==6: break

0 Comments