请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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 操作是合法的。示例 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 <= 9push、pop、peek 和 emptypop 或者 peek 操作)进阶:
O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。本题要使用栈来实现队列,所以需要先了解栈和队列分别有什么特性。
栈:先进后出;队列:先进先出
所以,要使用栈来模式队列的行为,如果仅仅用一个栈,是一定不行的,所以需要两个栈一个输入栈,一个输出栈,这里要注意输入栈和输出栈的关系。
在push数据的时候,只要数据放进输入栈就好,但在pop的时候,操作就复杂一些,输出栈如果为空,就把进栈数据全部导入进来(注意:全部导入),再从输出栈弹出数据,如果输出栈不为空,则直接从输出栈弹出数据就可以了。
最后如何判断队列为空呢?如果进栈和出栈都为空的话,说明模拟的队列为空了。
在代码实现的时候,会发现 pop() 和 peek() 两个函数功能类似,代码实现上也是类似的,所以我们可以思考一下如何把代码抽象一下。
我们在实现 peek() 函数时可以直接复用 pop() 函数,只不过最后需要把弹出的值再push进去。
class MyQueue {
public:
stack<int>stIn; // 定义输入栈
stack<int>stOut; // 定义输出栈
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
// 分两种情况讨论:输出栈为空、输出栈不为空
if(stOut.empty()) {
// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
while(!stIn.empty()) {
// 从stIn导入数据直到stIn为空
stOut.push(stIn.top());
stIn.pop();
}
}
int res = stOut.top();
stOut.pop();
return res;
}
int peek() {
int res = this->pop(); // 此处直接复用已有的pop函数
stOut.push(res); // 因为pop函数弹出了元素res,所以再push回去
return res;
}
bool empty() {
// 如果进栈和出栈都为空的话,说明模拟的队列为空
return stIn.empty()&&stOut.empty();
}
};
复杂度分析
时间复杂度: push和empty为O(1), pop和peek为O(n)