用栈实现队列,核心思想是使用两个先进后出的栈调转方向,使得两个栈具有队列先进先出的规则
class MyQueue {
//创建两个栈来调转方向
Stack<Integer> stackIn;
Stack<Integer> stackOut;
//创建MyQueue
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
//正常push进stackIn
public void push(int x) {
stackIn.push(x);
}
//pop方向不一样,想办法调转方向,创建一个函数dump
public int pop() {
dump();
//正常pop stackOut就行
return stackOut.pop();
}
public int peek() {
dump();
//正常peek就行
return stackOut.peek();
}
public boolean empty() {
//判断两个栈为空才是真的空
return stackIn.isEmpty() && stackOut.isEmpty();
}
//用来给stackin和stackOut调转方向
private void dump() {
//判断stackOut是否为空,为空才可以加元素,非空就返回
if(!stackOut.isEmpty()) {
return;
}
//往里加元素
while(!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/