【问题标题】:Remove from the tail of a linked list (Python)从链表的尾部删除(Python)
【发布时间】:2016-01-28 23:23:36
【问题描述】:

我是 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

谁能建议我哪里出错了?似乎节点对象被打印但不是节点内的值。提前感谢您的帮助!

【问题讨论】:

  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布代码并准确描述问题之前,我们无法有效地帮助您。您还没有包含类 Node。您还没有包含打印“已删除:”的代码。您可能打印的是 Node 对象,而不是其名称。
  • 你应该发布Node类。
  • Node 类没有提供给我,相反,我实现的代码需要与我假设的 Python 中 Node 类的通用实现一起使用。
  • 我仍然不清楚你想要什么输出。汽车->自行车->卡车,然后删除卡车。或卡车->自行车->汽车,然后删除汽车。

标签: python linked-list nodes


【解决方案1】:

remove_from_trail 方法返回的值是 Node 类型。当您打印它时,您正在打印该节点对象。需要访问节点内部的值,可以使用:

dir(result) 

查看对象有哪些方法和属性,然后调用你要查找的属性。

【讨论】:

  • 感谢您的快速回复!抱歉,我刚刚意识到无法编辑输出代码块 - 这是运行以检查我的代码是否正确实现的测试之一。因此,从 remove_from_tail 函数获取的代码需要采用正确的测试格式:result = my_list.remove_from_tail()
【解决方案2】:

看起来这段代码将从列表中删除所有节点。尝试类似:

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

【讨论】:

  • 感谢您的快速回复!我尝试实现您的代码编辑,但我仍然得到完全相同的输出。话虽如此,现在运行以检查我的代码是否正确实现的“测试”之一就是这个测试:'my_list = LinkedList() my_list.add(800) my_list.add(700) my_list.add (600) my_list.add(500) my_list.remove_from_tail() my_list.print_all()'
  • 对不起,用于测试成功的代码是:my_list = LinkedList() my_list.add(800) my_list.add(700) my_list.add(600) my_list.add(500) my_list.remove_from_tail() my_list.print_all() 但是另一个测试代码: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() 仍然产生相同的输出。
  • @blue_eclipse 问题出在print('Removed:', result)。试试print('Removed:', result.get_data())
  • 如果列表只有一个元素怎么办?在这种情况下,上面的代码不会改变任何东西。
猜你喜欢
  • 1970-01-01
  • 2018-07-31
  • 2014-07-03
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-06
  • 2018-11-24
相关资源
最近更新 更多