用两个栈来模拟实现队列
public class MyQueue {
private static Stack<Integer> inStack;
private static Stack<Integer> outStack;
public MyQueue(){
inStack = new Stack<>();
outStack = new Stack<>();
}
// 像队列中push元素
public void push(int x){
inStack.push(x);
}
// 从队列中弹出元素
public int pop(){
if (outStack.isEmpty()){
in2out();
}
return outStack.pop();
}
// 查看队首元素,但是不取出
public int peek(){
if(outStack.isEmpty()){
in2out();
}
return outStack.peek();
}
public boolean isEmpty(){
return inStack.isEmpty() && outStack.isEmpty();
}
public void in2out(){
while (!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
}
标签:笔试,outStack,Stack,面试,算法,isEmpty,push,inStack,public
From: https://www.cnblogs.com/dongyaotou/p/18564882