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

如何用链表读取指定输入并按要求打印?代码报错求助

解决链表打印与输入解析问题

嘿,咱们一步步来解决你的链表打印问题哈。我看你当前的代码里有几个关键问题,而且还缺少把输入解析成链表的逻辑,咱们逐个拆解:

1. 现有代码的核心问题

  • Node类定义错误:你把节点的数据存在了self.head,但标准链表节点应该用self.data存储值,这个命名错误会导致后续根本无法正确访问节点里的数值;另外next_In改成next_node会更规范,避免和Python内置的next函数混淆。
  • 打印函数逻辑错误:直接print(head)会打印Node对象的内存地址,而不是节点里的实际数值;递归的写法不仅没处理好终止逻辑,也不符合你需要的打印格式。
  • 缺失输入解析与链表构建:你没有处理给定的输入字符串,把它转换成链表节点的代码,这也是程序报错的核心原因之一。

2. 分步解决方案

第一步:修正链表节点类

先把Node类改成标准结构,确保能正确存储和访问节点数据:

class Node(object):
    def __init__(self, data=None, next_node=None):
        self.data = data  # 用data存储节点值,命名清晰规范
        self.next = next_node  # 指向下一个节点

第二步:解析输入并构建链表

你的输入5,0,3 3 3 ,34 43 54混合了逗号和空格作为分隔符,咱们先统一处理分隔符,提取出所有整数,再逐个构建链表:

def build_linked_list(input_str):
    # 把逗号替换成空格,按空格分割后过滤空字符串,转成整数列表
    nums = [int(num) for num in input_str.replace(',', ' ').split() if num.strip()]
    if not nums:
        return None  # 空输入返回空链表
    # 构建头节点
    head = Node(nums[0])
    current = head
    # 依次添加后续节点
    for num in nums[1:]:
        current.next = Node(num)
        current = current.next
    return head

第三步:实现正确的打印函数

根据问题要求,有两种打印方式可选:

版本1:每行打印一个元素(符合问题描述的要求)

def print_list(head):
    current = head
    while current is not None:
        print(current.data)  # 打印节点的实际数值
        current = current.next

版本2:空格分隔一行打印(匹配你给出的预期输出)

def print_list(head):
    result = []
    current = head
    while current is not None:
        result.append(str(current.data))
        current = current.next
    print(' '.join(result))  # 用空格拼接所有元素后打印

3. 完整可运行代码

把所有部分整合起来,测试你的输入:

class Node(object):
    def __init__(self, data=None, next_node=None):
        self.data = data
        self.next = next_node

def build_linked_list(input_str):
    nums = [int(num) for num in input_str.replace(',', ' ').split() if num.strip()]
    if not nums:
        return None
    head = Node(nums[0])
    current = head
    for num in nums[1:]:
        current.next = Node(num)
        current = current.next
    return head

def print_list(head):
    # 这里用匹配预期输出的版本,需要每行一个的话替换成版本1即可
    result = []
    current = head
    while current is not None:
        result.append(str(current.data))
        current = current.next
    print(' '.join(result))

# 测试输入
input_str = "5,0,3 3 3 ,34 43 54"
linked_list_head = build_linked_list(input_str)
print_list(linked_list_head)

运行这段代码后,输出就是你预期的:5 0 3 3 3 34 43 54

小提示

递归打印的方式虽然也能实现,但对于很长的链表可能会触发栈溢出,所以更推荐用循环遍历的方式哦。如果输入可能包含非整数内容,还可以添加异常处理来增强代码的健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:01:24