0

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
  • 2
    `del node3` only deleted the `node3` **reference** to the `node(3)` object, not this object itself. – Swifty Jan 28 '23 at 13:15
  • why node3 = None don't work. same reason? – keshavnischal Jan 28 '23 at 13:16
  • 2
    For the same reason; you just point the `node3` reference to another object (None in this case), but `node(3)` still exists, and `node2.next` still references it. – Swifty Jan 28 '23 at 13:18
  • Related: [How to delete every reference of an object in Python?](https://stackoverflow.com/questions/3013304/how-to-delete-every-reference-of-an-object-in-python) – sebtheiler Jan 28 '23 at 13:23

1 Answers1

-1

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.

Anurag Regmi
  • 629
  • 5
  • 12