class MyQueue {
//使用栈的方式来模拟实现队列。思路:用两个栈来完成
//但在pop的时候,操作就复杂一些,输出栈如果为空,就把进栈数据全部导入进来(注意是全部导入),
Stack<Integer> instack;
Stack<Integer> outstack;
public MyQueue() {
instack = new Stack<>();
outstack = new Stack<>();
}
public void push(int x) {
instack.push(x);
}
public int pop() {
dumpstackin();
return outstack.pop();
}
public int peek() {
dumpstackin();
return outstack.peek();
}
public boolean empty() {
return (instack.isEmpty() && outstack.isEmpty());
}
public void dumpstackin(){
//当发生pop和peek的时候调用该方法,具体步骤是移除instack中的所有元素并放入outstack中
if(!outstack.isEmpty()){return;}
//当outstack是空时
while(!instack.isEmpty()){
outstack.push(instack.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();
*/