问题描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。地址:牛客链接
问题分析
用 stack1 实现队列的Push操作,Push 时直接push进 stack1stack2 实现队列的 Pop 操作, Pop 时先检查 stack2 是否为空,若不为空,直接从stack2 进行Pop,若为空,需要将 stack1中的元素 pop 进 stack2,然后 stack2再 Pop出一个元素
经验教训
如何用两个栈来实现队列
上述方法如何用两个队列来实现栈的 Push 与 Pop 操作
代码实现
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 =
new Stack<Integer>();
Stack<Integer> stack2 =
new Stack<Integer>();
public void push(
int node) {
stack1.add(node);
}
public int pop() {
if (! stack2.isEmpty()){
return stack2.pop();
}
else {
while (! stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}