力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
/*
1.用栈实现队列
利用2个栈进栈出栈操作即可是实现队列
*/
class MyQueue {
Stack<Integer> inStack;
Stack<Integer> outStack;
public MyQueue() {
inStack = new Stack<Integer>();
outStack = new Stack<Integer>();
}
//直接进栈
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 empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
//inStack出栈操作
public void in2Out() {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
}