Implement Queue using Stacks
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) -- 将元素放入队尾。
- pop() -- 移除队列头的元素。
- peek() -- 返回队列头元素。
- empty() -- 返回队列是否为空。
- 只能使用栈的标准操作--即
push to top
,peek/pop from top
,size
,和 is empty 合法。 - 使用的语言不一定有栈结构,但可以使用链表或队列模拟栈,只要使用栈的标准操作就可以。
- 假设所有操作都合法(例如,当队列空时不会执行 pop 和 peek 操作)。
因为栈是 FILO 结构,队列是 LIFO 结构,入队操作和压栈操作一样,但是出栈操作和出队操作相反,可以使用辅助栈,出队时将数据压入辅助栈,返回栈底(队头)元素后再将元素存回原来的栈。
class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
squeue.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
stack<int> temp;
stackSwap(squeue, temp);
temp.pop();
stackSwap(temp, squeue);
return;
}
// Get the front element.
int peek(void) {
int ret = 0;
stack<int> temp;
stackSwap(squeue, temp);
ret = temp.top();
stackSwap(temp, squeue);
return ret;
}
// Return whether the queue is empty.
bool empty(void) {
return squeue.empty();
}
void stackSwap(stack<int> &src, stack<int> &dst)
{
int srcSize = src.size();
for(int i = 0; i < srcSize; ++i)
{
dst.push(src.top());
src.pop();
}
return;
}
private:
stack<int> squeue;
};