232. 用栈实现队列
![](https://img.haomeiwen.com/i14289546/0f790cc623189378.png)
image.png
解法
class MyQueue {
// 输入栈
private Stack<Integer> inStack;
// 输出栈
private Stack<Integer> outStack;
/** Initialize your data structure here. */
public MyQueue() {
inStack = new Stack<>();
outStack = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
inStack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (!outStack.isEmpty()) {
return outStack.pop();
}
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
return outStack.pop();
}
/** Get the front element. */
public int peek() {
int x = pop();
outStack.push(x);
return x;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
}
/**
* 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();
*/
本文标题:232. 用栈实现队列
本文链接:https://www.haomeiwen.com/subject/mdvtbltx.html
网友评论