https://leetcode-cn.com/problems/implement-queue-using-stacks/
今天学习用两个栈实现队列,主要就是熟悉一下栈的基本操作吧?这种蛮简单的。
import java.util.*;
class MyQueue {
Stack<Integer> stackIn = new Stack<>();//压入栈
Stack<Integer> stackOut = new Stack<>();//弹出栈
public MyQueue() {
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
if(!stackOut.isEmpty()){
return stackOut.pop();
}
else{
dumpToStackOut();//倒入弹出栈函数
return stackOut.pop();
}
}
public int peek() {
if(!stackOut.isEmpty()){
return stackOut.peek();
}
else{
dumpToStackOut();//倒入弹出栈函数
return stackOut.peek();
}
}
public boolean empty() {
if(stackIn.isEmpty() && stackOut.isEmpty()){
return true;
}
else return false;
}
private void dumpToStackOut(){
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();
*/