双向链表实现不起作用
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)
请参阅 string format examples 的 Python 文档。
并且,根据@Jeremy 的评论,您还需要将值分配给新节点并向节点 class 添加一个 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)
我是面向对象编程和这个站点的新手。
我已经为一个大学项目研究这个程序很长一段时间了(或者至少我正在尝试)。我必须创建一个处理双向链表的程序,更准确地说,我需要实现以下内容:
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)
请参阅 string format examples 的 Python 文档。
并且,根据@Jeremy 的评论,您还需要将值分配给新节点并向节点 class 添加一个 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)