Program to print node data at given index

 In this program we will see how we can print the node data at given index


class Node:
    def __init__(self,data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def display(self):
        temp = self.head
        while temp!=None:
            print(temp.data, end="-->")
            temp = temp.next
    def deleteAtGivenIndex(self,index):
        pos=1
        temp = self.head
        if index>self.length() or index<1:
            print("\nGiven Index is not valid!!")
        elif pos == index:
            self.head = self.head.next
        else:
            while temp!=None:
                pos = pos+1
                if pos==index:
                    temp.next = temp.next.next
                    
                else:
                    temp = temp.next
                    

    def length(self):
        temp = self.head
        count = 0
        while temp!=None:
            count = count+1
            temp = temp.next
        return count
if __name__=="__main__":
    llist = LinkedList()
    first = Node(10)
    second = Node(20)
    third = Node(30)
    fourth = Node(40)
    fifth = Node(50)
    llist.head = first
    first.next = second
    second.next = third
    third.next = fourth
    fourth.next = fifth
    llist.display()
    llist.deleteAtGivenIndex(2)
    print('\nAfter delete')
    llist.display()

No comments:

Post a Comment