LeetCode232 用栈实现队列
使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
思路和用队列实现栈一样,只需要注意push操作。
最后代码如下,提交到LeetCode一次成功
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stack<int> temp_s;
while (!s.empty())
{
int num = s.top();
s.pop();
temp_s.push(num);
}
s.push(x);
while (!temp_s.empty())
{
int num = temp_s.top();
temp_s.pop();
s.push(num);
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int num = s.top();
s.pop();
return num;
}
/** Get the front element. */
int peek() {
return s.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return s.empty();
}
private:
stack<int> s;
};