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

Python单链表打印报TypeError: __str__返回非字符串类型错误排查

问题排查:单链表打印抛出TypeError: __str__ returned non-string (type NoneType)

报错信息

执行print(sll)时,链表节点数据可以正常打印,遍历结束后抛出错误:

TypeError: str returned non-string (type NoneType)

根因定位

  • __repr__方法未按规范返回字符串
    Python中print()调用对象时,会依次查找对象的__str__、__repr__方法获取字符串输出,两个方法都必须返回str类型值。你的__repr__方法内部仅通过print()输出节点值,没有显式返回值,Python函数无显式return时默认返回None,遍历结束后解释器尝试将None作为字符串输出,直接触发类型错误。
  • 遍历过程直接修改链表头指针
    __repr__的循环中直接执行self.__head = self.__head.next_node,遍历完成后self.__head会指向链表尾节点,原链表的头引用被覆盖,后续所有链表操作都会丢失前面的节点数据。
  • 插入逻辑破坏初始哨兵节点
    sorted_insert方法第一次插入时直接将初始哨兵节点(值为0的占位节点)替换为业务节点,后续遍历逻辑会出现边界判断异常。

修复方案

  • 重写__repr__:使用临时指针遍历链表,不修改原头节点;将所有节点值拼接为字符串后返回,不在方法内部直接执行print
  • 简化sorted_insert逻辑:保留哨兵头节点作为固定起点,遍历找到插入位置的前驱节点后完成插入,不需要单独判断第一次插入的分支

修复后可运行代码

class Node:
    """ Node class """

    def __init__(self, data, next_node=None):
        """ initializes private variable data"""
        self.__data = data
        self.__next_node = next_node

    @property
    def data(self):
        return self.__data

    @data.setter
    def data(self, value):
        if not isinstance(value, int):
            raise TypeError("data must be integer")
        self.__data = value

    @property
    def next_node(self):
        return self.__next_node

    @next_node.setter
    def next_node(self, value):
        if value != None and not isinstance(value, Node):
            raise TypeError("next_node must be a Node object")
        self.__next_node = value


class SinglyLinkedList:
    """creates a sorted linked list"""

    def __init__(self):
        # 哨兵头节点,不存储实际业务数据
        self.__head = Node(0)

    def __repr__(self):
        node_values = []
        cur = self.__head.next_node
        while cur is not None:
            node_values.append(str(cur.data))
            cur = cur.next_node
        return '\n'.join(node_values)

    def sorted_insert(self, value):
        new_node = Node(value)
        cur = self.__head
        while cur.next_node is not None and cur.next_node.data < value:
            cur = cur.next_node
        new_node.next_node = cur.next_node
        cur.next_node = new_node


def main():
    sll = SinglyLinkedList()
    sll.sorted_insert(2)
    sll.sorted_insert(5)
    sll.sorted_insert(3)
    sll.sorted_insert(10)
    sll.sorted_insert(1)
    sll.sorted_insert(-4)
    sll.sorted_insert(-3)
    sll.sorted_insert(4)
    sll.sorted_insert(5)
    sll.sorted_insert(12)
    sll.sorted_insert(3)
    print(sll)

if __name__ == "__main__":
    main()

运行结果

执行后按升序输出所有节点值,无类型错误,链表结构可复用:

-4
-3
1
2
3
3
4
5
5
10
12

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 21:54:18