解题思路
栈:先进后出,队列:先进先出
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();//当做主队列
Stack<Integer> stack2 = new Stack<Integer>();//当做辅助
//入栈函数
public void push(int num) {
stack1.push(num);//直接用栈的push方法
}
//出栈函数
public int pop() {
Integer a=null;
//如果栈2不是空的,那么把最上面那个取出来
if(!stack2.empty()){
a=stack2.pop();
}
else{
//如果栈2是空的,就把栈1里的数一个个取出来,放到栈2里
while(!stack1.empty()){
a=stack1.pop();
stack2.push(a);
}
//栈2里有数之后,再次把里面的数取出来
if(!stack2.empty()){
a=stack2.pop();
}
}
return a;
}
}