leetcode225. 用队列实现栈
https://leetcode-cn.com/problems/implement-stack-using-queues/
使用队列实现栈的下列操作:
思路
(这里要强调是单向队列queue, 而不是双向队列deque)
队列模拟栈,其实一个队列就够了,那么我们先说一说两个队列来实现栈的思路。
队列是先进先出的规则,把一个队列中的数据导入另一个队列中,数据的顺序并没有变,并有变成先进后出的顺序。
所以用栈实现队列, 和用队列实现栈的思路还是不一样的,这取决于这两个数据结构的性质。
但是依然还是要用两个队列来模拟栈,只不过没有输入和输出的关系,而是另一个队列完全用又来备份的!
如下面动画所示,用两个队列que1和que2实现队列的功能,que2其实完全就是一个备份的作用,把que1最后面的元素以外的元素都备份到que2,然后弹出最后面的元素,再把其他元素从que2导回que1。
模拟的队列执行语句如下:
queue.push(1);
queue.push(2);
queue.pop(); // 注意弹出的操作
queue.push(3);
queue.push(4);
queue.pop(); // 注意弹出的操作
queue.pop();
queue.pop();
queue.empty();
C++代码
两个队列实现
class MyStack {
public:
queue<int> que1;
queue<int> que2; //备份队列
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
//入栈元素放入que1
que1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
//删除que1中最后一个元素
int size = que1.size();
size--; //保留que1中最后一个要删除元素
while (size--)
{
//备份到que2中
que2.push(que1.front());
que1.pop();
}
//移除栈顶元素
int result = que1.front();
que1.pop();
//再将备份元素重新放入que1中
que1 = que2;
//最后清空备份队列que2
while (!que2.empty())
{
que2.pop();
}
return result;
}
/** Get the top element. */
int top() {
//取栈顶元素, 直接调用queue队列的back()接口
return que1.back();
}
/** Returns whether the stack is empty. */
bool empty() {
//que1队列为空, 栈为空
return que1.empty();
}
};
一个队列实现
一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时在去弹出元素就是栈的顺序了。
class MyStack {
public:
//一个队列实现,一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时在去弹出元素就是栈的顺序了。
queue<int> que;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
//一个队列实现
que.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
//一个队列实现
int size = que.size();
size--; //保留要移除元素
while (size--)
{
que.push(que.front());
que.pop();
}
int result = que.front();
que.pop();
return result;
}
/** Get the top element. */
int top() {
return que.back();
}
/** Returns whether the stack is empty. */
bool empty() {
return que.empty();
}
};
公众号:代码随想录