I don't understand why in line 31 of my code, it needs to be while(temp.next): instead of while(temp):Can someone please help me understand? I am new and confused. Here is my code for my Linked List:
class Node():
def __init__(self, data):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def printlist(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
def append(self, new_data):
new_node = Node(new_data)
if self.head == None:
self.head = new_node
else:
temp = self.head
#if I replace the following line with "while(temp):" instead of
#"while(temp.next)"it will not work. Why?
while(temp.next):
temp = temp.next
temp.next = new_node
mylist = LinkedList()
mylist.head = Node(1)
mylist.append(2)
mylist.printlist()
CodePudding user response:
while (temp) will ensure that temp is falsy (None) when the loop exits. But then the statement below that loop will fail:
temp.next = new_node
...as there is no next attribute when temp is None.
The goal of this while loop is to find the last node. The distinguishing characteristic of the last node is that its next attribute is None, so that explains the while condition. As long as this node still has a successor, it is not the last node, and we should step forward. That is what this loop is doing.
