'弹出' Ruby中的方法

时间:2017-07-06 01:43:43

标签: ruby linked-list stack nodes pop

我创造了一个' pop'从链表中取出最后一个节点的方法。但是,我收到的问题是它没有删除节点,它只是告诉我节点中应该删除的数据。

我应该在前言中使用测试驱动开发,然后编写测试来说明' assert_equal" blop",list.pop。 " blop"是最后一个节点的值。很高兴我的方法告诉我,但它仍然没有删除节点。

def pop
 @count -= 1
 return_string = ""
 current_node = @head
 until current_node.next_node == nil
  current_node = current_node.next_node
 end
 return_string << current_node.data + " "
 return_string.strip
 current_node.next_node = Node.new(data)
end

我的问题是如何返回被删除内容的值,以及从链接列表中删除值。

1 个答案:

答案 0 :(得分:0)

until current_node.next_node == nil
    current_node = current_node.next_node
end

当该循环结束时,current_node指向最后一个节点(下一个节点为“nil”的节点)。

这是您应删除的节点,但为了删除该节点,您应该将上一个节点的next_node指向nil

但是,此时您没有对前一个节点的引用。

您可以使用另一个变量来跟踪previous节点,以便在退出循环后将其删除。

您可以查看此相关问题(非特定于Ruby)以获取有关算法的想法。

Linked List implementation for a stack

作为旁注,其中一个答案实现了这一点,即使pop删除列表的第一个节点(并push将节点添加到开头),这样可以更容易(而且速度更快,因为每次都不会遍历整个列表。)