Program to delete a linked list

 In this program we will see how we can delete a linked list


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 deleteLinkedList(self):
        while self.head!=None:
            temp =self.head
            self.head = self.head.next
            del temp

    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.deleteLinkedList()
    print('\nAfter delete')
    llist.display()
    

No comments:

Post a Comment