- ques:用两个栈实现队列功能
- ans:与225一样的思路,看完225大佬们的题解之后能很轻松的想出思路,用s1来实现真正模拟队列中的元素顺序,借助s2辅助完成这一排序
- 代码实现
#include<iostream>
#include<stack>
using namespace std;
class MyQueue {
private:
stack <int> s1;//s1作为模拟队列的栈,即s1的出栈即为队列出队的顺序
stack <int> s2;
public:
MyQueue() {
}
void push(int x) {
if(s1.size()>0)
{
int n = static_cast<int>(s1.size());
int t = n;
while(n--)
{
s2.push(s1.top());
s1.pop();
}
s1.push(x);
while(t--)
{
s1.push(s2.top());
s2.pop();
}
}
else
s1.push(x);
}
int pop() {
int top = s1.top();
s1.pop();
return top;
}
int peek() {
return s1.top();
}
bool empty() {
return s1.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
参考其他人做双队列实现栈的功能时候用到的强制类型转换,static_cast<int>(...)
以及循环控制需要两个变量,即n和t;
以及使用while(n--)来作为循环判断条件(都是和dl学滴~)
while(n--)是先判断循环条件n,再执行自减操作
标签:LeetCode232,MyQueue,队列,s1,实现,int,push,top From: https://www.cnblogs.com/mingyuer/p/18073654