题目描述
请用栈实现一个队列,支持如下四种操作:
push(x) – 将元素x插到队尾;
pop() – 将队首的元素弹出,并返回该元素;
peek() – 返回队首元素;
empty() – 返回队列是否为空;
注意:
你只能使用栈的标准操作:push to top,peek/pop from top, size 和 is empty;
如果你选择的编程语言没有栈的标准库,你可以使用list或者deque等模拟栈的操作;
输入数据保证合法,例如,在队列为空时,不会进行pop或者peek等操作;
解题思路
第一题:初始化stack:首先定义容器stack和缓存cache,然后声明MyQueue类函数
第二题:将x元素放在队列最后面:直接stk.push添加一个x数据即可
第三题:去掉在队列最前面的元素并且输出那个元素:
首先为了方便定义一个copy函数引入一个stack a和stack b,通过while循环将a最上方的元素移动到stack b
然后将这个元素从stack a删除,也就是stack a后来者居上,stack b就变成按顺序排列的了,此时stack a最
底下的元素就会被放置于stack b的最上方.
然后再主函数中,首先我们运行copy函数,然后定义整型变量res用于储存cach(也就是stack b)最上方的元素
储存好以后将这个元素从stack b里面删除,再运行copy函数还原原来的stack a(这个时候删掉的不会出现)
最后返回值就是之前res储存的元素
第四题:得到最前面的元素(在stack最底下的元素)
因为之前使用了main函数,这次我们使用peek避免程序错误(当然随便你),然后运行一次我们上面定义的copy函数.还是定义一个整型变量res用于储存最前面的元素,不用删除,得到结果再按照原来的顺序放好,返回res
第五题:判断stack是否为空
布尔表达式判断,empty和pop一样是可以直接调用的
注意:为什么pop(),empty(),top()后面都有括号?
因为这些都是成员函数,不加括号编译器无法识别导致错误
C++ 代码
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int>stk,cache;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stk.push(x);
}
/** Removes the element from in front of queue and returns that element. */
void copy(stack<int> &a, stack<int> &b) {
while (a.size()) {
b.push(a.top());
a.pop();
}
}
int pop() {
copy(stk, cache);
int res = cache.top();
cache.pop();
copy(cache, stk);
return res;
}
/** Get the front element. */
int peek() {
copy(stk, cache);
int res = cache.top();
copy(cache, stk);
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return stk.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/
篇章
上一篇:AcWing 17. 从尾到头打印链表
https://www.acwing.com/solution/content/212445/
下一篇:AcWing 53. 最小的k个数
https://www.acwing.com/solution/content/213211/