原文链接 [每日 LeetCode] 232. Implement Queue using Stacks
Description:
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
Example:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
Notes:
- You must use_only_standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
思路:本题要求用 stack 结构来实现队列的基本操作。由于队列的特点是先进先出,所以考虑使用两个 stack 来操作,一个 input 和一个 output,当 output 栈空时,从 input 栈中弹出元素压进 output 栈,如此一来即可实现后进的后出。
C++ 代码
class MyQueue {
stack<int> input, output;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
input.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int temp = peek();
output.pop();
return temp;
}
/** Get the front element. */
int peek() {
if (output.empty())
while(input.size()){
output.push(input.top());
input.pop();
}
return output.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return input.empty() && output.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();
*/
运行时间:4ms
运行内存:9M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于