题目

https://leetcode-cn.com/problems/implement-queue-using-stacks/
思路
用两个栈倒腾,让元素的顺序反转两次,就回到了原始顺序
stackIn是正常栈中顺序,stackOut是反转顺序- 每次
push总是往stackIn里加 - 每次
pop/peek- 如果
stackOut里面非空,那么在stackOut中pop/peek - 如果
stackOut里面为空而且stackIn不为空,那么就将stackIn中的全部元素直接push到stackOut中

- 如果
code
java
class MyQueue {
Deque<Integer> stackIn = new ArrayDeque<>();
Deque<Integer> stackOut = new ArrayDeque<>();
public MyQueue() {
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
if(empty()) return -1;
if(!stackOut.isEmpty()){
return stackOut.pop();
}else{
int count=stackIn.size();
for(int i=0;i<count;i++){
stackOut.push(stackIn.pop());
}
return stackOut.pop();
}
}
public int peek() {
if(empty()) return -1;
if(!stackOut.isEmpty()){
return stackOut.peek();
}else{
int count=stackIn.size();
for(int i=0;i<count;i++){
stackOut.push(stackIn.pop());
}
return stackOut.peek();
}
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
}