题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:只要入栈,全部push到栈1;出栈,当栈2为空,把栈1的数据全部pop到栈2,栈2不空,依次pop栈2即可。
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
本文介绍了一种使用两个栈来实现队列的方法。通过将所有入队操作压入栈1,而出队操作则先判断栈2是否为空,若为空则将栈1的所有元素依次弹出并压入栈2,最后从栈2中弹出顶部元素实现队列的先进先出特性。
477

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



