web123456

‘NoneType’ object has no attribute ‘val’ type error analysis

Question asked: Writing inversionLink ListWhen you are in the question, you want to first obtain the val in each node of the forward linked list, and then rely on inversion to assign values ​​to each node, so that you can reverse the linked list in performance without cross-assignment between pointers. (In fact, the connection order of linked lists in memory has not changed)

I encountered this problem when I got all the vals of the entire linked list:

linklist=[]
cur=head
a=1
while a!=None:
    a=cur.val
    cur=cur.next
    linklist.append(a)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Prompt says a= There is a problem with this sentence: ‘NoneType’ object has no attribute ‘val’

Actually it is because when the loop runs to the last time (theoretically, where it should stop), at this time:
1, a=val of the tail node
2,cur==None
3. Add a A at the end of the linklist

It should end, but the end condition is not met, so the next loop is entered, at this time:
To assign the value to a, but cur=None, None is an object belonging to 'NoneType', it does not have the attribute of .val, which leads to an error.

So how to modify it?

Just modify the end of the loop, for example:

linklist=[]
cur=head
a=1
while cur!=None: #Modify loop conditions
    a=cur.val
    cur=cur.next
    linklist.append(a)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Summary: The problem similar to '####' object has no attribute '###' is that it fails to figure out who the object has become.