我正在努力寻找一种在Ruby的LinkedList struct 上实现#POP的解决方案.目前我的实现已经到了删除最后一个元素(将倒数第二个 node 上的@next_node
个元素设置为nil
)并返回新的最后一个元素的地步,但我需要我的方法来记住并返回我循环过的所有以前的 node ,我正在努力找到一种方法来做到这一点.有谁能帮帮我:
LinkedList示例 struct ;
"#<LinkedList:0x000000010ced2508 @head=#<Node:0x000000010ced22b0 @value=13, @next_node=#<Node:0x000000010ced22d8 @value=2, @next_node=#<Node:0x000000010ced2300 @value=25, @next_node=#<Node:0x000000010ced2328 @value=20, @next_node=nil>>>>>"
我目前的#POP实现:
def pop
return if head.nil?
current_node = head
current_node = current_node.next_node until current_node.next_node.next_node.nil?
current_node.next_node = nil
return current_node
end
根据@tom-Lord的答复,更新了工作方法:
def pop
if head.nil?
return head
elsif head.next_node.nil?
self.head = nil
return head
else
second_last_node = head
second_last_node = second_last_node.next_node until second_last_node.next_node.next_node.nil?
last_node = second_last_node.next_node
second_last_node.next_node = nil
return last_node
end
end