希望有人可以在这里给我一个提示 - 所以我有一个Node类,应该收到1个强制值和一个可选值。想法是返回一个链表
class Node(object):
def __init__(self, value, next_node = None):
self.value = value
self.next_node = next_node
def get_next(self):
return self.next_node
现在我正在使用此类创建一个链接列表,如:
Z = Node('Z')
Y = Node('Y', Z)
X = Node('X', Y)
W = Node('W', X)
现在我想编写一个接收列表头部并打印它的函数:
def print_reverse(head):
current = head
my_list = []
while current:
current = current.next_node
u = Node(current)
my_list.append(u.value)
print my_list
print_reverse(W)
我遇到的问题是我找回了内存地址而不是实际值。
[<__main__.Node object at 0x1033eb390>, <__main__.Node object at 0x1033eb350>, <__main__.Node object at 0x1033eb310>, None]
基本上我不知道如何实例化Node的值。我想回到这个
[ W, X, Y , Z, None]
答案 0 :(得分:1)
class Node(object):
def __init__(self, value, next_node = None):
self.value = value
self.next_node = next_node
def get_next(self):
return self.next_node
def print_reverse(head):
current = head
my_list = []
my_list.append(current.value)
while current.next_node != None:
current = current.next_node
my_list.append(current.value)
print my_list
Z = Node('Z')
Y = Node('Y', Z)
X = Node('X', Y)
W = Node('W', X)
print_reverse(W)
这会为我运行并打印['W','X','Y','Z']。
答案 1 :(得分:0)
您需要实现 repr ,它应返回对象的可打印表示形式。例如
class Node(object):
def __init__(self, value, next_node = None):
self.value = value
self.next_node = next_node
def get_next(self):
return self.next_node
def __repr__(self):
return self.value
https://docs.python.org/2/reference/datamodel.html#object.repr