1,题目要求
Implement the following operations of a stack using queues.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
empty() – Return whether the stack is empty.
Notes:
You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
用一个队列模拟一个栈的操作:包括push,pop,top,empty操作。
2,题目思路
因为用栈模拟队列时,可以用两个栈来实现。于是想到是否可以用两个队列来模拟栈?
首先,关于队列:
C++队列Queue是一种容器适配器,它给予程序员一种先进先出(FIFO)的数据结构。
C++队列Queue类成员函数如下:
- back()返回最后一个元素
- empty()如果队列空则返回真
- front()返回第一个元素
- pop()删除第一个元素
- push()在末尾加入一个元素
- size()返回队列中元素的个数
队列的基本操作:
- queue入队,如例:q.push(x); 将x 接到队列的末端。
- queue出队,如例:q.pop(); 弹出队列的第一个元素,注意,并不会返回被弹出元素的值。
- 访问queue队首元素,如例:q.front(),即最早被压入队列的元素。
- 访问queue队尾元素,如例:q.back(),即最后被压入队列的元素。
- 判断queue队列空,如例:q.empty(),当队列空时,返回true。
- 访问队列中的元素个数,如例:q.size()
对于队列来模拟栈并不是必须两个队列,只要保证在队列每新进元素都 变成队列中的第一个元素即可。
即,每次新进入一个元素后,都将原先前面的元素一次排到新进入数字的后方,就可以模拟一个栈的形式了。
3,程序源码
class MyStack {
public:
/** Initialize your data structure here. */
queue<int> q;
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q.push(x);
for(int i = 0;i<q.size()-1;i++)
{
q.push(q.front());
q.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int res = q.front();
q.pop();
return res;
}
/** Get the top element. */
int top() {
return q.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
};