题目链接
题目描述
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x)将元素 x 推到队列的末尾int pop()从队列的开头移除并返回元素int peek()返回队列开头的元素boolean empty()如果队列为空,返回true;否则,返回false示例
示例1:
输入: [“MyQueue”, “push”, “push”, “peek”, “pop”, “empty”] [[], [1], [2], [], [], []] 输出: [null, null, null, 1, 1, false]
解释: MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
提示
1 <= x <= 9- 最多调用
100次push、pop、peek和empty 假设所有操作都是有效的 (例如,一个空的队列不会调用
pop或者peek操作)思路
双栈
设置两个栈
stackIn,stackOut:void push(int x)直接将元素加入stackIn即可。int pop()若stackOut为空,则将stackIn栈顶弹出并压入stackOut中,直到stackIn为空,然后弹出stackOut栈顶;若stackOut不为空,则直接弹出stackOut栈顶。int peek()返回队列开头的元素,返回stackOut栈顶,若stackOut为空,则将stackIn栈顶弹出并压入stackOut中,直到stackIn为空boolean empty(),当两个栈都为空的时候返回真。题解
```cpp class MyQueue { private: stack
stackIn; stack stackOut; void move() {
while (!stackIn.empty()) {stackOut.push(stackIn.top());stackIn.pop();}
}
public: /* Initialize your data structure here. / MyQueue() { }
/* Push element x to the back of queue. / void push(int x) {
stackIn.push(x);}
/* Removes the element from in front of queue and returns that element. / int pop() {
if (stackOut.empty()) { this->move(); } int ret = stackOut.top(); stackOut.pop(); return ret;}
/* Get the front element. / int peek() {
if (stackOut.empty()) { move(); } return stackOut.top();}
/* Returns whether the queue is empty. / bool empty() {
return stackIn.empty() && stackOut.empty();} };
/**
- 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();
- bool param_4 = obj->empty();
*/
```
复杂度分析
- 时间复杂度:
- 空间复杂度:
