我必须使用两个堆栈实现一个队列,这是问题定义
在这个挑战中,您必须首先使用两个堆栈实现一个队列。 然后处理查询,其中每个查询是以下之一 类型:
1 x:将元素放入队列末尾。 2:出列 队列前面的元素。 3:打印前面的元素 队列中的。
这是我的解决方案
object Solution {
import scala.collection.mutable
import scala.io.StdIn.{readInt, readLine}
def init(): (Int => Unit, () => Int, () => Int) = {
val stack = mutable.Stack[Int]()
val interim = mutable.Stack[Int]()
def move(source: mutable.Stack[Int], target: mutable.Stack[Int]): Unit = {
while (source.nonEmpty) {
target.push(source.pop())
}
}
def enque(it: Int): Unit = {
move(stack, interim)
stack.push(it)
move(interim, stack)
}
def deque() = stack.pop()
def top()= stack.head
(enque, deque, top)
}
def main(args: Array[String])={
val (enque, deque, top) = init()
val n = readInt()
for(i <-1 to n){
val t1 = readLine().split(" ").map(x=>x.toInt)
t1 match {
case Array(1, n) => enque(n)
case Array(2) => deque()
case Array(3) => println(top())
}
}
}
}
有17个测试用例。它在 10 个测试用例上运行良好,其他 7 个测试用例给出错误“由于超时而终止”。
我的解决方案有什么问题?不知道Scala有没有快速栈
根据测试,将队列压入堆栈而不做其他任何事情可能会有所帮助。等到出队或 print front 被调用后再弹出并推送到第二个堆栈。