题解 | #用两个栈实现队列#
用两个栈实现队列
http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
队列特性:先进先出
栈特性:先进后出
import java.util.Stack;
/*
队列:先进先出
栈:先进后出
*/
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>(); //栈1--push
Stack<Integer> stack2 = new Stack<Integer>(); //栈2--pop
public void push(int node) {
while(!stack2.isEmpty()){ //每次push前先将栈2清空放入栈1(保证先进的在栈2底)
stack1.push(stack2.pop());
}
stack1.push(node); //元素进栈
}
public int pop() {
while(!stack1.isEmpty()){ //每次pop前先将栈1清空放入栈2(保证后进的在栈1底)
stack2.push(stack1.pop());
}
return stack2.pop();
}
}