[LintCode]Implement Queue by Two Stacks
public class Solution {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public Solution() {
// 2015-09-03
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int element) {
stack1.push(element);
}
public int pop() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public int top() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
}
本文介绍了一种使用两个栈来实现队列的方法。通过定义两个栈stack1和stack2,实现了队列的基本操作:push、pop和top。当进行push操作时,元素直接压入stack1;进行pop或top操作时,如果stack2为空,则将stack1中的所有元素依次弹出并压入stack2,最后返回stack2的弹出元素或顶部元素。
277

被折叠的 条评论
为什么被折叠?



