自定义链表添加元素时出现TypeError: 'Node' object is not callable错误的排查与修改方案
Fixing Your Custom Linked List Errors & Proper Element Addition
1. Why You're Getting the TypeError
The immediate issue is in your show() method:
def show(self): node=self.head() # ❌ Wrong! self.head is an attribute, not a callable method while node is not None: print(node.data) node=node.next
self.head stores a Node object (or None when the list is empty) — it's a variable, not a function. Removing the parentheses will fix this error:
def show(self): node=self.head # ✅ Correct, access the attribute directly while node is not None: print(node.data) node=node.next
2. Proper Way to Add Elements to Your Linked List
Right now you're manually linking nodes by setting listt.head and listt.head.next, which works for 2 elements but gets messy quickly. Let's add an add() method to the Linked class to handle this automatically (we'll implement adding elements to the end of the list, a common use case):
Step-by-Step Implementation:
- If the list is empty (
self.headisNone), set the new node as the head. - If the list isn't empty, traverse to the last node (where
node.nextisNone) and set itsnextattribute to the new node.
Full Corrected & Improved Code
class Node: def __init__(self, data=None): self.data = data self.next = None class Linked: def __init__(self): self.head = None def show(self): node = self.head # Fixed: no parentheses while node is not None: print(node.data) node = node.next def add(self, data): # Create a new node with the given data new_node = Node(data) # If list is empty, make this the head if self.head is None: self.head = new_node return # Traverse to the last node current = self.head while current.next is not None: current = current.next # Link the new node to the end current.next = new_node # Test the improved linked list listt = Linked() listt.add("4") listt.add("5") listt.add("6") # Now adding more elements is easy! listt.show()
3. Testing the Code
When you run this, it will output:
4 5 6
No more errors, and adding elements is clean and scalable.
内容的提问来源于stack exchange,提问作者user16843837
相关产品推荐
相关产品推荐

