Home > front end >  'NoneType' object has no attribute 'val' in Python Linked List
'NoneType' object has no attribute 'val' in Python Linked List

Time:11-26

I have recently started to practice using LinkedList in Python and encountered the problem below. Both code seems like they are doing the same thing but 1 got the error while the other did not. Can someone let me know why this is the case?:

#Python Linked List
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

Assume we have linkedlist node = ListNode{val: 2, next: ListNode{val: 4, next: ListNode{val: 3, next: None}}}

#Code 1: (This can run fine and will print 2 4 3)
while node:
    print(node.val) # access the values of the node by node.val
    node=node.next`

#Code 2: (This gives me an error saying 'NoneType' object has no attribute 'val' while still printing 2)
node = node.next
print(node.val)

I expect to see code 2 not giving me the error.

CodePudding user response:

After your while loop finished you are at the last node in your linked list. So node.next will point to None as per your definition:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

CodePudding user response:

According to your code, you have set the default values for the properties "val" as 0, "next" as None. If supposed that you have created an instance, None will be assigned to the "next" property of the instance. If you want to access to the "next" property, create another instance and assign it to the "next" property of the previous instance

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
   
node1 = ListNode()
node2 = ListNode()

node1.next = node2
print(node1.next)
  • Related