Python实现链表插入打印时报错'int' object has no attribute 'data'求解
问题原因
- 核心错误在
add_at_end方法的最后一行:你已经基于新值newval创建了节点对象newnode,但实际赋值给尾部节点next属性的是原始int值newval,而非节点对象。后续打印链表遍历到这个int值时,尝试访问.data属性就触发了报错。 - 次要问题:
add_at_end方法没有定义返回值,直接打印该方法调用结果会输出None,可按需调整。
修正后可运行代码
class node(): def __init__(self, data): self.data = data self.next = None class linkedlist(): def add_at_end(self,newval,head): newnode = node(newval) while head.next: head = head.next # 修正为赋值节点对象而非原始int值 head.next = newnode def print_list(self,head): LL = [] while head: LL.append(head.data) head = head.next return LL x = node(5) y = node(6) z = node(2) x.next = y y.next = z vals = linkedlist() # add_at_end为原地修改链表,无返回值无需打印 vals.add_at_end(8,x) print(vals.print_list(x))
运行后输出结果为:[5, 6, 2, 8],符合预期。
内容的提问来源于stack exchange,提问作者vivek shankar
相关产品推荐
相关产品推荐

