题目描述:使用队列实现栈的入栈,出栈,返回栈顶元素,栈判空的功能。
解题思路:看到很多博友都选择使用两个队列实现栈,我之前写过一篇两个栈实现队列的博文,如有需要,可以互相对比着看。但是在这道题中,其实使用一个队列即可实现栈,相比于使用两个队列实现栈,会更加清晰易懂。
- 入栈:入栈其实只需使队列入队,但为了为后面的出栈服务,需要将入队后的队列前 n-1 个元素依次移动到队列的后面;
- 出栈:将队列的 front 出栈即可,注意要先将队列的 front 暂存,用于最后返回值;
- 栈顶元素:直接返回队列的 front 即可;
- 判空:判断队列是否为空即可;
C++实现如下:
class MyStack {
public:
/** Initialize your data structure here. */
queue<int> q;
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.
int pop()
{
int res;
if(q.empty())
return 0;
else
res = q.front();
q.pop(); //注意这里一定要出队才能使栈中元素出栈,不然只会返回栈顶元素的值而栈不变
return res;
}
// Get the top element.
int top() {
if(q.empty())
return 0;
else
return q.front();
}
// Return whether the stack is empty.
bool empty() {
return q.empty();
}
};