昨天的任务实现是太难了,难以完成打卡,也许以后学会了可以补上,今天的任务就简单多了,主要是栈与队列的问题
栈和队列是一种数据结构,栈先进后出,队列先进先出,这个还是知道的
做题吧,今天就两道题
232.用栈实现队列
题目链接:232. 用栈实现队列
其实原理很简单,就是想要大家熟悉一下栈和队列的结构和用法,我们用两个栈就可以模拟队列了,输出的时候把第一个栈放到第二个栈,顺序就和队列一样了

代码如下:
class MyQueue {
public:
//两个栈
stack<int>in;
stack<int>out;
MyQueue() {
}
void push(int x) {
//直接放
in.push(x);
}
int pop() {
if(out.empty()){
while(!in.empty()){
out.push(in.top());
in.pop();
}
}
//注意清除
int res = out.top();
out.pop();
return res;
}
int peek() {
int res = this->pop();
out.push(res);
return res;
}
bool empty() {
return in.empty() && out.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();
*/
225. 用队列实现栈
题目链接如下:225. 用队列实现栈
其实这道题一个队列都可以完成
我们把队列前size()-1个数依次弹出再加回去,不就跟栈的顺序一样了吗?
