两个栈实现队列
简单思路
入队压栈就行,出队弹栈并压栈至另一个栈,直到为空,出队一个元素之后再压栈回去
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() {
while(!stack1.isEmpty()){ //弹栈并压栈至另一个栈
stack2.push(stack1.pop());
}
int result = stack2.pop(); //出队
while(!stack2.isEmpty()){ //再压栈回去
stack1.push(stack2.pop());
}
return result;
}
}
巧解思路
栈二不为空则从栈二弹栈,栈二为空则按思路一,不需要再压栈回栈一
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())
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int result = stack2.pop();
return result;
}
}