剑指Offier——用两个栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
while (!stack2.empty()){
stack1.push(stack2.peek());
stack2.pop();
}
stack1.push(node);
}
public int pop() {
while (!stack1.empty()){
stack2.push(stack1.peek());
stack1.pop();
}
int peek = stack2.peek();
stack2.pop();
return peek;
}
}
本文介绍了一种使用两个栈来实现队列的方法。通过在两个栈之间转移元素,可以实现队列的先进先出特性。文章提供了一个具体的Java实现案例。
700

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



