我是Python的新手,在实现从链表中删除最后一个节点的函数时遇到了麻烦。这是我到目前为止的代码(我在一个名为Coderunner的在线平台上编码,它已经为我实现了一些后台代码,例如Node类):
class LinkedList:
def __init__(self):
self.head = None
def print_all(self):
current = self.head
while current != None:
print(current.get_data())
current = current.get_next()
def add(self, item):
new_node = Node(item)
new_node.set_next(self.head)
self.head = new_node
def remove_from_tail(self):
current = self.head
prev = current
while current != None:
current = current.get_next()
prev.set_next(current.get_next())
return current
运行以下代码时:
my_list = LinkedList()
my_list.add('Car')
my_list.add('Bike')
my_list.add('Truck')
result = my_list.remove_from_tail()
print('Removed:', result)
my_list.print_all()
我明白了:
Removed: <__main__.Node object at 0x1063650>
Bike
Truck
有谁可以建议我哪里出错了?似乎节点对象被打印但不是节点内的值。在此先感谢您的帮助!
答案 0 :(得分:0)
方法remove_from_trail返回的值是Node类型。当您打印它时,您正在打印该Node对象。您需要访问节点内的值,您可以使用:
dir(result)
查看对象具有哪些方法和属性,然后调用您要查找的属性。
答案 1 :(得分:0)
看起来此代码将从列表中删除所有节点。尝试类似:
def remove_from_tail(self):
current = self.head
prev = current
while current.get_next() != None: #the last element will have next == None
prev = current
current = current.get_next()
# At this point, current will be pointing to the last element in the list
prev.set_next(None)
return current