单链表头部插入元素报错:AttributeError: 'LinkedList'无insert_head属性
单链表头部插入报错的问题修复
问题根源
- 构造函数语法错误:
LinkedList类的构造函数写成了_init_,Python要求类的构造函数必须使用双下划线包裹(__init__),否则该方法不会被自动执行,导致self.head和self.n未被初始化。 - 方法归属错误:
insert_head和__len__方法被错误定义在Node类中,这两个方法是链表的核心操作逻辑,应该属于LinkedList类。
修正后的代码
class LinkedList: def __init__(self): # 修正为双下划线的构造函数 self.head = None self.n = 0 def __len__(self): # 移到LinkedList类中 return self.n def insert_head(self, value): # 移到LinkedList类中 new_node = Node(value) new_node.next = self.head self.head = new_node self.n += 1 class Node: def __init__(self, value): self.data = value self.next = None # 插入5个元素以得到预期输出5 L = LinkedList() L.insert_head(1) L.insert_head(2) L.insert_head(3) L.insert_head(4) L.insert_head(5) print(len(L)) # 输出5
说明
- 修正构造函数后,实例化
LinkedList时会正确初始化头部节点和元素计数器。 - 将链表操作方法移到
LinkedList类后,调用L.insert_head()就不会出现属性不存在的错误。 - 连续调用5次
insert_head后,len(L)会返回5,符合预期输出。
内容的提问来源于stack exchange,提问作者Subhadip Guchhait
相关产品推荐
相关产品推荐

