剑指Offer P68 面试题9:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
Stack的相关API: boolean empty() :测试堆栈是否为空。 Object peek( ):查看堆栈顶部的对象,但不从堆栈中移除它。 Object pop( ):移除堆栈顶部的对象,并作为此函数的值返回该对象。 Object push(Object element):把项压入堆栈顶部。 int search(Object element):返回对象在堆栈中的位置,以 1 为基数。 Queue(阻塞队列)的相关API: add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常 |
import java.util.Stack;
public class Solution
{
Stack<Integer> stack1 = new Stack<Integer>(); // stack1用于入队操作
Stack<Integer> stack2 = new Stack<Integer>(); // stack2用于出队操作
public void push(int node)
{
stack1.push(node);
}
public int pop() throws Exception
{
// 将stack1的数据转移到stack2
if (stack2.empty())
{
while (!stack1.empty())
{
stack2.push(stack1.pop());
}
}
if (stack2.empty())
throw new Exception("queue is empty");
return stack2.pop();
}
}