题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路
当stack2中不为空时,在stack2中的栈顶元素是最先进入队列的元素,直接弹出。 如果stack2为空,把stack1中的元素逐个压入stack2.由于先进入队列的元素被压到stack1的低端,经过弹出和压入之后,就处于stack2的顶端,可以直接弹出。
实现
public class T07 {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() throws Exception {
if (!stack2.isEmpty()) {
return stack2.pop();
}
if (stack2.isEmpty()) {
if (stack1.isEmpty()) {
throw new Exception("queue is empty");
}
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}