请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
- void push(int x) 将元素 x 推到队列的末尾
- int pop() 从队列的开头移除并返回元素
- int peek() 返回队列开头的元素
- boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:
你只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/implement-queue-using-stacks
主要思路:
-
需要两个栈进行队列模拟的操作,一个栈无法模拟
-
栈分为出栈和进栈,模拟入队操作,无特殊情况,直接将数据压入“进栈即可”,模拟出队情况,比较特殊,先要判断“出栈”中是否有元素,若没有,将“入栈”中的数据压入“出栈”,(注意要全部“压入”),然后再从“出栈”元素模拟出队操作。若有,直接将“出栈”元素出队。
-
还要注意的一点是: JDK的官方文档不建议使用Stack实现栈的功能,转而使用Deque接口的ArrayDeque实现栈的功能。 所以,我们使用Deque模拟栈操作。
代码实现:
class MyQueue {
Deque<Integer> inStack;
Deque<Integer> outStack;
public MyQueue() {
inStack =new ArrayDeque<Integer>();
outStack=new ArrayDeque<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();//注意这里的peek是outStart本身具有的函数,不要搞混,歧义、其他的也是类似
}
public boolean empty() {
return inStack.isEmpty()&& outStack.isEmpty();
}
private void in2out(){
while(!inStack.isEmpty()){//注意这里使用的while,要把“入栈”中的全部元素先放到“出栈”
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();
*/