You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python链表问题:数字字符串转链表仅打印首个节点值求助

问题排查与修复

代码问题分析

你的代码无法正确构建链表的核心原因有两个:

  1. 未维护链表尾部指针:第一次创建root后,curr_node始终为None,后续创建新节点时没有将其链接到已有的链表上。
  2. 错误更新尾部指针:在else分支中,创建新节点后直接将curr_node赋值为curr_node.next(也就是None),导致新节点完全脱离链表结构,根本没和之前的节点产生关联。

修正后的代码

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

total = "523"
root = None
curr_node = None

for digit in total:
    new_node = ListNode(int(digit))
    if root is None:
        # 初始化链表头,同时让尾部指针指向头节点
        root = new_node
        curr_node = root
    else:
        # 将新节点链接到当前链表尾部
        curr_node.next = new_node
        # 更新尾部指针到新的节点
        curr_node = curr_node.next

while root:
    print(root.val)
    root = root.next

关键修改说明

  • 每次循环先创建新节点,统一节点创建逻辑,避免重复代码。
  • 初始化链表后,让curr_node始终指向链表的尾部节点,这样后续可以直接在尾部添加新节点。
  • 新增节点时,通过curr_node.next = new_node完成链表的链接,再移动curr_node到新的尾部,保证下一次添加节点时能找到正确的位置。

内容的提问来源于stack exchange,提问作者BWallDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 19:09:33