简单:
232 用栈实现队列
https://leetcode.cn/problems/implement-queue-using-stacks/submissions/
解答:
思路:用两个栈来实现,倒一下即刻。
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 reslut = out.top();
out.pop();
return reslut;
}
int peek() {
int reslut = this->pop();
out.push(reslut); //因为pop函数弹出了元素res,所以再添加回去
return reslut;
}
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. 用队列实现栈
解答:
思路:
两个队列来实现栈。其中一个队列是用来暂存数据的。也就是先将队列1中的元素都放到队列2中,只留下最后一个元素作为输出,然后在讲队列2中的元素放回队列1后,将队列2清空;反复此操作。
class MyStack {
public:
queue<int> q1;
queue<int> q2;
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
int size=q1.size();
while(size!=1){
q2.push(q1.front());
q1.pop();
size--;
}
int result=q1.front();
q1.