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

Python链表反转方法仅返回原表头,其余节点丢失问题求助

问题修复与解释

核心问题

你的反转链表逻辑差了关键一步:反转完成后没有更新链表的head指针。循环结束时,prev已经指向原链表的最后一个节点(也就是反转后的新表头),但你没有把self.head赋值为prev,导致原表头a依然是链表的头节点,而它的next已经被改成None,所以打印时只会显示a -->。

另外,方法里的if act is not None完全多余,外层while循环已经确保act不为None,去掉不会引发NoneType错误。

修正后的代码

class Nodo:
    def __init__(self, data = None, next = None):
        self.data = data
        self.next = next


class Lista_enlazada:
    def __init__(self):
        self.head = None

    def agregar_al_inicio(self, data):
        self.head = Nodo(data=data, next=self.head)

    def reves(self):
        act = self.head
        prev = None
        while act is not None:
            siguiente = act.next  # 先保存下一个节点,防止修改当前节点next后丢失引用
            act.next = prev       # 反转当前节点的指向
            prev = act            # prev指针移动到当前节点
            act = siguiente       # act指针移动到下一个节点
        self.head = prev  # 关键:将链表头更新为反转后的第一个节点

    def print_list( self ):
        node = self.head
        while node != None:
            print(node.data, end =" --> ")
            node = node.next

lista = Lista_enlazada()
lista.agregar_al_inicio(1)
lista.agregar_al_inicio(2)
lista.agregar_al_inicio(3)
lista.agregar_al_inicio("a")

lista.reves()
lista.print_list()

运行结果

执行后会输出:1 --> 2 --> 3 --> a -->

关于你提到的第二种方法的补充

如果是遍历原链表并反向插入新链表时返回内存地址,大概率是你直接将Nodo对象加入列表并打印了,而不是打印节点的data属性。比如应该把每个节点的data取出添加到新链表,或者打印时访问node.data而不是直接打印node。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 05:12:39