写链表时报错AttributeError: 'int' object has no attribute 'next'

跟敲链表代码时,遇到点小问题,请老师们帮忙解答下。
环境

Python: 3.7.7

代码如下:

class LinkNode:

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

    def append(self, data=None):
        while self.next is not None:
            self = self.next

        self.next = LinkNode(data)
        return self

    def travel(self):
        while self.next is not None:
            print(self.data)
            self = self.data

class TestLink:

    def __init__(self):
        self.link = LinkNode(0)
        self.link.append(1)
        self.link.append(2).append(3).append(4).append(5)
        self.link.travel()

testlink = TestLink()

运行时报错如下:
image

修改一下

def travel(self):
        while self.next is not None:
            print(self.data)
            self = self.next   # 这里

对,这里写错了,感谢 :rofl:

你是要做算法题 还是只是了解一下链表知识额

随便看看 :grinning:

关闭