题目: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.
- Notes:
- You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is 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).
题目分析:
- 题目含义是用两个栈来模拟队列,包含队列中的出队、入队、判断空、取队尾元素等
思路:
- 定义两个栈a和b
- 判断队空:如果栈a和b都为空,那么队列为空
- 入队:首先判断对是否满,若栈a不满,那么直接将元素入栈到栈a中;若栈a满了,将栈a中的元素依次入栈到栈b中,再将元素入栈到栈a中
- 出队:如栈b为空,先将栈a中的全部元素入栈到栈b中,再将栈b中栈顶元素出栈;如栈b不为空,直接出栈b的栈顶元素
- 获取队尾元素:如栈b为空,先将栈a中的全部元素入栈到栈b中,再获取栈b中栈顶元素;如栈b不为空,直接获取栈b的栈顶元素
代码:
*C++:
class Queue {
public:
stack<int> a;//用作入队的时候进入a栈
stack<int> b;//用作出队的时候出去b栈
void move()//元素的移动函数 将所有栈a中的元素都入栈到栈b中
{
while(!a.empty())//当栈a不为空时
{
int x=a.top();//获取栈a的栈顶元素
a.pop();//栈a弹出栈顶元素
b.push(x);//栈b中进入x元素值
}
}
// Push element x to the back of queue.
void push(int x) {//入队操作相当于将元素入栈到栈a中
a.push(x);//栈a中入栈x元素
}
// Removes the element from in front of queue.
void pop(void) {
if(b.empty())//如果栈b是空的,那么将栈a中所有元素入栈到栈b中
{
move();
}
if(!b.empty())//如果栈b不为空,那么出队就是相当于栈b的栈顶元素出栈
{
b.pop();
}
}
// Get the front element.
int peek(void) {
if(b.empty())//如果栈b是空的,那么将栈a中所有元素入栈到栈b中
{
move();
}
if(!b.empty())//如果栈b不为空,那么取栈b的栈顶元素
{
return b.top();
}
}
// Return whether the queue is empty.
bool empty(void) {
return a.empty()&&b.empty();//如果a栈和b栈都为空,那么队列就为空
}
};