[232. 用栈实现队列]
「这是我参与2022首次更文挑战的第38天,活动详情查看:2022首次更文挑战」。
题目描述
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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(双端队列)来模拟一个栈,只要是标准的栈操作即可。
示例
示例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 操作) 进阶: 你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。
思路
这道题考察的是对基本数据结构栈和队列的掌握程度,不涉及特定的算法。栈的特点是先进后出,队列的特点是先进先出。区别在于出的顺序不一样,为了实现改变出的顺序,需要使用两个栈,称为输入栈和输出栈,对数据进行两次先进后出,就颠倒过来了。对于push操作,直接push到输入栈中,pop操作和peek操作,需要将输入栈的数据全部转移到输出栈中,由于栈的特性,这次转移就完成了输入顺序的还原,符合队列的要求,在转移完毕后,此时对输出栈执行pop或peek就完成pop要求,empty操作则是需要同时检查两个栈。其余细节见代码。
代码实现
细节见注释,peek的写法是为了精简搬运元素代码的重复。
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stack_in.push(x); //直接进输入栈
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(stack_out.empty()){
while(!stack_in.empty()){ //转移数据
stack_out.push(stack_in.top());
stack_in.pop();
}
} int result=stack_out.top(); //输出输出栈首个
stack_out.pop();
return result;
}
/** Get the front element. */
int peek() {
int result=this->pop(); //从输出栈里取出首元素,再放回去,不影响输出栈
stack_out.push(result);
return result;
}
/** Returns whether the queue is empty. */
bool empty() {
return stack_in.empty()&&stack_out.empty(); //同时检查
}
private:
stack<int> stack_in; //输入栈
stack<int> stack_out; //输出栈
};
/**
* 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();
*/
总结
简要的介绍了栈和队列两基本的数据结构。