dong123qwe 2008-6-21 23:04
2008-06-21 Ruby 测试题(00020)
栈与队列
根据栈的先进后出,队列先进先出的原理
push N次字符 pop M次,打印pop获得的字符
e.g 栈:push(“a”),push(“b”),push(“c”)
pop
输出:c
pop
输出:b
队列:push(“a”),push(“b”),push(“c”)
pop
输出:a
pop
输出:b
sandybuster 2008-6-23 09:33
[code]class Stack
def initialize(m)
@stack=m
end
def push(m)
@stack<<m
end
def pop()
if @stack.empty?
puts "the stack is empty"
else
puts @stack.delete_at(@stack.length-1)
end
end
end
aStack=Stack.new([])
aStack.push(1)
aStack.push(2)
aStack.pop()#=>2
aStack.push(3)
aStack.pop()#=>3
aStack.pop()#=>1
aStack.pop()#=>the stack is empty
class Queue
def initialize(n)
@queue=n
end
def push(n)
@queue<<n
end
def pop()
if @queue.empty?
puts "the queue is empty"
else
puts @queue.delete_at(0)
end
end
end
aQueue=Queue.new([])
aQueue.push(1)
aQueue.push(2)
aQueue.pop()#=>1
aQueue.push(3)
aQueue.pop()#=>2
aQueue.pop()#=>3
aQueue.pop()#=>the stack is empty[/code]