why deleting a node of linked list using del in python does not automatically changes the previous node's next pointer to None

111 Views Asked by At

I created a linked list using 3 node. Then I deleted the last node using del keyword I also tried assigning last node None. When I printed the linked list, no change was there

Why is it not working. please guide me about the concept I am missing Thank You

class node:
    def __init__(self, data):
        self.data= data
        self.next = None
    def printLL(self):
        temp = self
        while(temp):
            print(temp.data, end=" ")
            temp = temp.next
        print("None")
        print()

# creating linked list
head = node(1)
node2 = node(2)
node3 = node(3)
head.next = node2
node2.next = node3
head.printLL()

#deleting the last node
del node3
# or
# node3 = None

head.printLL()

output

1 2 3 None

1 2 3 None

expected output

1 2 3 None

1 2 None
1

There are 1 best solutions below

0
Anurag Regmi On

You need to implement the delete function separately.

You need to set next of second last node to None

node2.next = None

del node3

Have a look at this for more detail.