链表实现报错:AttributeError: 'NoneType' object has no attribute 'next_node'
AttributeError: 'NoneType' object has no attribute 'next_node' in Linked List Insertion Hey there! Let's break down this frustrating error you're hitting when adding the second node to your linked list—this is one of the most common gotchas for folks new to implementing linked lists, so we’ll get this sorted out quickly.
What’s Causing This Error?
This message means you’re trying to access the next_node attribute of a None object. In your case, when inserting the second node, somewhere in your code you’re treating a None value like it’s a valid Node instance, and trying to read/write its next_node property.
The Most Common Mistake (And How to Fix It)
Let’s walk through a typical faulty implementation that triggers this error, then fix it.
Example of Broken Code
Suppose your linked list and node classes look like this, with an insert method that’s supposed to add nodes to the end:
class Node: def __init__(self, data): self.data = data self.next_node = None class LinkedList: def __init__(self): self.head = None def insert(self, data): new_node = Node(data) # Wrong approach to find the end of the list current = self.head while current: current = current.next_node # Now current is None, so this line throws the error! current.next_node = new_node
Why This Fails
- When you insert the first node,
self.headgets set to that node, and itsnext_nodeisNone. - When inserting the second node, the loop runs until
currentbecomesNone(since it keeps followingnext_nodeuntil there’s nothing left). - Then you try to set
current.next_node = new_node—butcurrentisNone, hence theAttributeError.
Corrected Insert Method
We need to stop at the last valid node (the one whose next_node is None), then attach the new node to it:
class LinkedList: def __init__(self): self.head = None def insert(self, data): new_node = Node(data) # Handle empty list case first if self.head is None: self.head = new_node return # Traverse to the last valid node current = self.head while current.next_node is not None: current = current.next_node # Now current is the last node—attach the new node here current.next_node = new_node
Other Things to Check
If your insertion logic is for a different position (like inserting after a specific node), double-check these:
- Always verify that the node you’re trying to modify (e.g., the predecessor node for your new node) is not
Nonebefore accessing itsnext_node. - Make sure you’re not accidentally overwriting
self.heador losing track of node pointers during insertion.
内容的提问来源于stack exchange,提问作者Pouya Jigsaw

