题目:
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.
- 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).
翻译:
使用栈实现以下队列的操作。
- push(x) -- 将元素 x 压入队列。
- pop() -- 从队列头移除元素。
- peek() -- 获得第一个元素。
- empty() -- 返回队列是否为空。
注意:
- 你需要使用标准的栈操作--就是说只有
push to top
,peek/pop from top
,size
和 is empty 操作是有效的。 - 依赖于你使用的语言,栈可能不会被支持。 只要您只使用栈的标准操作,你可以使用列表或双端队列(双端队列)来模拟栈。
- 你可以假设所有操作都是有效的(举例,没有pop或peek操作在空的队列中调用)。
思路:
使用两个栈来模拟队列,格外注意 push 操作,直接见代码。
C++代码(Visual Studio 2017):
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> s1;
stack<int> s2;
int front;
/** Push element x to the back of queue. */
void push(int x) {
if (s1.empty())
front = x; //Please pay more attention here, It's 'front = x;' .
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
s2.push(x);
while (!s2.empty()) {
s1.push(s2.top());
s2.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int n = s1.top();
s1.pop();
return n;
}
/** Get the front element. */
int peek() {
return s1.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return s1.empty();
}
};