Skip to main content

data structures || linked list

 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

Popular posts from this blog

Class and object Task 1| cinema tickets | hacker rank|tcs fresco play

  class   Movie :      def   __init__ ( self , nameofmovie , nooftickets , totalcost ):          self . nameofmovie = nameofmovie          self . nooftickets = nooftickets          self . totalcost = totalcost      def   __str__ ( self ):          return   "Movie : " + str ( self . nameofmovie ) + "\n" + "Number of Tickets : " + str ( self . nooftickets ) + "\n" + "Total Cost : " + str ( self . totalcost )                   # Write your code here if   __name__  ==  '__main__' :

Magic constant generator -python3/hacker rank solution / tcs fresco play

  def   generator_Magic ( n1 ):      # the value starts from 3 and m is formula for constant,      #for generator  yield should use      for   a   in   range ( 3 , n1 + 1 ):          m = a * ( a ** 2 + 1 ) / 2          yield   m               # Write your code here if   __name__  ==  '__main__' :

Handling Exceptions 1 | hacker rank solution

  #!/bin/python3 import   math import   os import   random import   re import   sys # # Complete the 'Handle_Exc1' function below. # # def   Handle_Exc1 ():      a = int ( input ())      b = int ( input ())      if   a > 150   or   b < 100 :          raise   ValueError   ( "Input integers value out of range." )        if   a + b > 400 :          raise   ValueError ( "Their sum is out of range" )      print ( "All in range" )      # Write your code here if   __name__  ==  '__main__' :      try :          Handle_Exc1 ()   ...