入队,正常入栈
出队,借助第二个栈,若第二个栈为空,将第一个栈全部移动到第二个栈;不为空,正常出栈
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.push(node);
}
public int pop() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
该博客介绍了一种使用两个栈来模拟队列操作的方法。push操作直接入栈1,pop操作时如果栈2为空,则将栈1所有元素移到栈2,然后从栈2弹出元素,确保了队列的先进先出特性。
102

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



