这道题目是要求你使用stack简单地构建一个queue,实现和正常的queue的push,pop,front功能。
比较经典的一道题目了,也加深我们对栈和队列的理解。
描述:
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.
实现上述接口即可,并且题目中都给出了是int型的队列,所以不用用模板template了。
大致的思路如下:
1.入队列,仅仅将元素存储在arr1中即可。
2.查找的时候,因为要看最开始进入栈arr1的元素,也就是最底下的元素,这时候我们将所有元素倾倒到arr2中。
3.这时候的arr2支持队列的peek(front)和pop操作,因为无论你看还是删除,都是对arr2的top元素进行操作。并且注意一点:这里只有pop操作会影响其他操作,在arr2没被删空之前,只需要将之后push的元素存放在arr1中,arr2空了再一次执行倾倒操作。
class Queue {
public:
stack<int> arr1;
stack<int> arr2;
// Push element x to the back of queue.
void push(int x) {
arr1.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
if(arr2.empty()){
while(!arr1.empty()){
arr2.push(arr1.top());
arr1.pop();
}
}
arr2.pop();
}
// Get the front element.
int peek(void) {
if(arr2.empty()){
while(!arr1.empty()){
arr2.push(arr1.top());
arr1.pop();
}
}
return arr2.top();
}
// Return whether the queue is empty.
bool empty(void) {
return arr1.empty()&&arr2.empty()?1:0;
}
};