lifelonglearner
lifelonglearner

Reputation: 326

Why does this while loop end? node5 is not NoneType. (Traversing Linked Lists)

Code below. I understand conceptually that the loop ends because self.next of the final node = None, but we're checking to see that node != None, and type(node5) returns __main__.LinkedListNode, which is not None. So how does node != None ever return False, ending the while loop?

class LinkedListNode():

    def __init__(self,value):
        self.value = value
        self.next = None #This is the next point, is initially None

    def traverseList(self):
        node = self #Start at the Head Node
        while node != None:
            print(node.value) #Access the node value
            node = node.next #Move to the next link in the list

#Create nodes for list
node1 = LinkedListNode('Mon')
node2 = LinkedListNode('Tues')
node3 = LinkedListNode('Wed')
node4 = LinkedListNode('Thurs')
node5 = LinkedListNode('Fri')

node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5

node1.traverseList()

type(node5)

Upvotes: 1

Views: 82

Answers (2)

JDunken
JDunken

Reputation: 463

The problem is that on the final iteration node gets set to None because node5 has a next of None. You can avoid this by breaking out of the loop when this condition is encountered...

def traverseList(self):
        node = self #Start at the Head Node
        while node != None:
            print(node.value) #Access the node value
            if node.next is None:
                break
            else:
                node = node.next #Move to the next link in the list

Upvotes: 0

CDJB
CDJB

Reputation: 14516

You're not checking if type(node5) = None, your while loop checks if node != None.

At the final iteration, node holds node5, so print(node.value) prints Fri, node = node.next sets node to None, as we never set node5's next attribute, and then the while loop terminates.

Upvotes: 1

Related Questions