双链接列表实现不工作

2024-03-28 17:26:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我是面向对象编程和这个网站的新手。在

我为一个大学项目做这个项目已经有一段时间了(至少我正在努力)。我必须创建一个处理双重链接列表的程序,更准确地说,我需要实现以下内容:

  • class Node
  • class LinkedList
  • 各种方法。在

到目前为止,我的代码是这样的:

class Node:
    def __init__(self):
        self.value = None
        self.next_node = None
        self.previous_node = None

class LinkedList(object):
    def __init__(self):
        self.first = None
        self.last = None

    def __str__(self):
        return 'This is the value: '.format(self.first)

    def append(self, value):
        new_node = Node()
        self.first = new_node

def main():
    myList = LinkedList()
    myList.append(20)
    print(myList)

我希望输出是:"This is the value: 20"。在

但是我得到的输出是:"This is the value: "。在

我的错误是什么?我的append方法或我的__str__方法不能正常工作(或者两者都不能)。(可能是很明显的事情)


Tags: the方法selfnonenodeisvaluedef
1条回答
网友
1楼 · 发布于 2024-03-28 17:26:32

{}添加到字符串中,告诉format将值放在哪里。在

def __str__(self):
    return 'This is the value: {}'.format(self.first)

有关string format examples,请参阅Python文档。在

而且,根据@Jeremy的评论,您还需要将该值赋给新节点,并向Node类添加一个str()函数。在

这应该是有效的:

^{pr2}$

相关问题 更多 >