【发布时间】:2019-12-13 23:39:42
【问题描述】:
我正在尝试创建一个最小堆栈函数,但我想我不明白循环的大小,这是我的代码:
class Node
attr_accessor :value, :next_node
def initialize(value, next_node = nil)
@value = value
@next_node = next_node
end
end
class LinkedList
def initialize
@head = nil
@tail = nil
end
def add(number)
new_node = Node.new(number)
if @head.nil?
@head = new_node
@tail = new_node
else
@tail.next_node = new_node
@tail = new_node
end
end
def add_at(index, number)
new_node = Node.new(number)
if @head.nil?
@head = new_node
@tail = new_node
else
current = @head
if index.zero?
new_node.next_node = @head
@head = new_node
puts @head
else
(index - 1).times do
current = current.next_node
end
new_node.next_node = current.next_node
current.next_node = new_node
puts new_node
end
end
end
def get(index)
current = @head
index.times do
current = current.next_node
end
current.value
end
def remove(index)
if @head.nil?
puts 'The list is already empty ^^'
else
if index.zero?
@head = @head.next_node
puts @head
else
current_at = @head
(index - 1).times do
current_at = current_at.next_node
end
tmp = current_at.next_node
current_at.next_node = tmp.next_node
puts tmp
end
end
end
def get_head
@head
end
end
class Stack
def initialize
@stack = LinkedList.new
end
def push(value)
@stack.add_at(0, value)
end
def pop
raise 'Stack is already empty' unless @stack
temporal = @stack.get(0)
@stack.remove(0)
#temporal
end
def min
current = @head
(@stack.size).times do
if current.next_node < current
current = current.next_node
end
end
current.value
end
def get_head
@stack.get_head
end
def get_stack
@stack
end
end
stack = Stack.new
stack.push(3)
stack.push(5)
puts stack.min
# => 3
stack.pop
stack.push(7)
puts stack.min
# => 3
stack.push(2)
puts stack.min
# => 2
stack.pop
puts stack.min
# => 3
当然,这会抛出:
#<Node:0x0000560189f7b490>
undefined method `size' for #<LinkedList:0x0000560189f7b4e0>
(repl):90:in `min'
(repl):109:in `<main>'
使用https://repl.it编译
ruby 2.5.5p157(2019-03-15 修订版 67260)[x86_64-linux]
这样做的目的是创建一个堆栈,其中包含一个 min 方法,该方法返回堆栈中的最小数字。
我正在尝试使用 Do 循环创建 min 函数,但它不起作用,我做错了什么?
【问题讨论】:
标签: ruby data-structures