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

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__' :

Getting Started with NumPy: A Comprehensive Guide

  NumPy is a fundamental library for scientific computing with Python. It provides support for large, multi-dimensional arrays and matrices, along with mathematical functions to operate on these arrays. This tutorial will introduce you to the basics of NumPy and its core functionalities. Installing NumPy Before diving into NumPy, make sure you have it installed. You can install NumPy using the following command: pip install numpy pip install numpy Importing NumPy Once installed, you can import NumPy in your Python script or Jupyter notebook as follows: import numpy as np Now, let's explore some of the essential features of NumPy. NumPy Arrays NumPy's primary data structure is the array. An array is a grid of values, and it can be one-dimensional or multi-dimensional. Here's how you can create a simple one-dimensional array: import numpy as np # Creating a one-dimensional array arr1 = np.array([1, 2, 3, 4, 5]) print(arr1) For multi-dimensional arrays, you can use nested ...

Difference between Numpy and Python list

  NumPy and Python lists are both data structures used to store collections of data, but they have several key differences: 1. Homogeneity:    - NumPy arrays are homogeneous, meaning that all elements in a NumPy array must have the same data type (e.g., all integers, all floating-point numbers). This homogeneity allows for efficient, element-wise operations.    - Python lists can contain elements of different data types, providing more flexibility but potentially sacrificing performance. 2. Performance:    - NumPy is optimized for numerical operations and is typically faster than Python lists when performing element-wise operations (e.g., addition, multiplication) on large datasets. This is due to the homogeneous nature of NumPy arrays and the fact that NumPy operations are implemented in C and can take advantage of low-level optimizations.    - Python lists are more versatile but are generally slower for numerical computations compared to Nu...