Reputation: 47
I code a program that creates a single linked list and now I am trying to delete the entire list.
First, I assign self.head to a variable, called current, but the function didn't work,and the program prints the entire list.
"""
def deleteLinkedList(self):
current = self.head
while current is not None:
nextNode = current.next
current = None
current = nextNode
"""
Result:
But, when I change the code, the program print the list is empty.
New code:
"""
def deleteLinkedList(self):
while self.head is not None:
nextNode = self.head.next
self.head = None
self.head = nextNode
"""
Result:
I couldn't understand why the second code works and the first not. Why the nodes were not deleted when I use a variable instead of self.head?
Upvotes: 0
Views: 80
Reputation: 141
If you print memory address of current and self.head you will see that they are not the same because when you do current = None, current point to an another memory case (which contains the None value) but it doesn't affect your self.head variable. That's why your list is not empty with your first code.
def delete(self):
current = self.head
print("current adress = " + hex(id(current)))
print("self.head adress = " + hex(id(self.head)))
while current is not None:
nextNode = current.next
current = None
print("current adress = " + hex(id(current)))
print("self.head adress = " + hex(id(self.head)))
current = nextNode
output :
current adress = 0x7f9304ecdcd0 //print before while current = self.head so same address
self.head adress = 0x7f9304ecdcd0
current adress = 0x90a9f0 //current = None so current address change
self.head adress = 0x7f9304ecdcd0 //self.head doesn't change
current adress = 0x90a9f0
self.head adress = 0x7f9304ecdcd0
Upvotes: 1