繁体   English   中英

双链列表实现不起作用

[英]Doubly-linked list implementation not working

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

我已经在大学项目的这个程序上工作了一段时间(或者至少我正在尝试)。 我必须创建一个处理双向链接列表的程序,更确切地说,我需要实现以下内容:

  • 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__方法无法正常工作(或都无法正常工作)。 (这可能确实很明显)

在字符串中添加{} ,以告知格式将值放置在何处。

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

有关字符串格式示例,请参见Python文档。

并且,根据@Jeremy的注释,您还需要将值分配给新的Node并向Node类添加str ()函数。

这应该工作:

class Node:
    def __init__(self, value=None):
        self.value = value # <- store the value in the object
        self.next_node = None
        self.previous_node = None

    def __str__(self):             # <- return the value as a string
        return str(self.value)

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(value) # <- pass value to the Node
        self.first = new_node
main()
    myList = LinkedList()
    myList.append(20)
    print(myList)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM