题目描述
实现一个MyQueue类,该类用两个栈来实现一个队列。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
你只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
解题思路与代码
双栈法
这道题不难,只要你了解栈这种数据结构的用法就行。在C++中,栈其实是没有begin(),end()这种内置方法的。所以我们在往另一个栈中去放元素的时候,需要将第一个栈中的元素挨个取出,然后再压入第二个栈中。
所以,我们就可以写出如下操作,具体请看代码:
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> first;
stack<int> second;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
while(!second.empty()){
int temp = second.top();
second.pop();
first.push(temp);
}
first.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while(!first.empty()){
int temp = first.top();
second.push(temp);
first.pop();
}
int temp = second.top();
second.pop();
return temp;
}
/** Get the front element. */
int peek() {
while(!first.empty()){
int temp = first.top();
second.push(temp);
first.pop();
}
return second.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return first.empty() && second.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();
*/
复杂度分析:
时间复杂度:push()与empty()函数的时间复杂度为O(1),而pop()和peek()函数的时间复杂度均摊一下,也是O(1)。对于每个元素,最多出栈和入栈2次。故时间均摊复杂度为O(1)
空间复杂度:O(n)。其中n是操作总数,我们如果要向栈中push n个元素了话,那空间复杂度就是O(n)。
总结
这道题不亏为一道简单题,稍微想一下,就能写出来了。