来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-stack-using-queues
题目描述:
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
输入:
[“MyStack”, “push”, “push”, “top”, “pop”, “empty”]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]
解题思路:
- 不管底层用什么结构实现,永远保证数据先进后出的一个逻辑数据结构,即栈
- 借助队列实现栈,可以使用两个队列,也可以只是用一个队列,本解只借助一个队列即可
- 入栈,即把数据进行入队,为了保证栈的特性先进后出,因此需要在push方法中对入队之前的所有元素进行一次出队入队操作,以保证所有数据达到先进后出的顺序
- 出栈,由于队列数据顺序已经调整,所以只需取队头元素即可
class MyStack {
public:
MyStack() {
}
void push(int x) {
if(!_q1.empty())
{
_q1.push(x);
}
else
{
_q2.push(x);
}
}
int pop() {
queue<int>* emptyQ = &_q1;
queue<int>* nonemptyQ = &_q2;
if(!_q1.empty())
{
swap(emptyQ,nonemptyQ);
}
//非空数值倒入到空队列中
while(nonemptyQ->size() > 1)
{
emptyQ->push(nonemptyQ->front());
nonemptyQ->pop();
}
int top = nonemptyQ->front();
nonemptyQ->pop();
return top;
}
int top() {
if(!_q1.empty())
{
return _q1.back();
}
else
{
return _q2.back();
}
}
bool empty() {
return _q1.empty() && _q2.empty();
}
queue<int> _q1;
queue<int> _q2;
};