题目描述
用两个栈来实现一个队列,完成队列的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()){
int i = stack2.pop();
stack1.push(i);
}
stack1.push(node);
}
public int pop() {
while(!stack1.empty()){
int i = stack1.pop();
stack2.push(i);
}
return stack2.pop();
}
}
优化:
while(!stack1.empty()){
int i = stack1.pop();
stack2.push(i);
}
//可以改成
while(!stack1.empty()){
stack2.push(stack1.pop());
}