补2月2
232.用栈实现队列
题目链接:https://leetcode.cn/problems/implement-queue-using-stacks/
文章讲解:https://programmercarl.com/0232.%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97.html
视频讲解:https://www.bilibili.com/video/BV1nY4y1w7VC
状态:对这块的实现没有接触过,很懵逼
思路
用一个输入栈和一个输出栈来模拟先入先出的队列。其中有一个点需要特别注意,每次pop的时候,都要确保输出的栈为空时才从输入栈中拿走所有元素
代码实现
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
stackIn.push(x);
}
int pop() {
if(stackOut.empty()){
while(!stackIn.empty()){
stackOut.push(stackIn.top());
stackIn.pop();
}
}
int res = stackOut.top();
stackOut.pop();
return res;
}
int peek() {
int res = this -> pop();
stackOut.push(res);
return res;
}
bool empty() {
return stackIn.empty() && stackOut.empty();
}
public :
stack<int> stackIn;
stack<int> stackOut;
};
/**
* 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();
*/
22.用队列实现栈
题目链接:https://leetcode.cn/problems/implement-stack-using-queues/
文章链接:https://programmercarl.com/0225.%E7%94%A8%E9%98%9F%E5%88%97%E5%AE%9E%E7%8E%B0%E6%A0%88.html
视频链接:https://www.bilibili.com/video/BV1Fd4y1K7sm
状态:还是不会
思路
主要是学会一个队列实现栈的思想,输入没问题,输出的时候,我们应该把队列最后一个元素的之前的所有元素都先出队列再入队列,然后到原先最后一个的时候,就是要输出的元素
代码实现
①一个队列实现栈
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size();
size --;
while(size --){
que.push(que.front());
que.pop();
}
int res = que.front();
que.pop();
return res;
}
int top() {
return que.back();
}
bool empty() {
return que.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
②两个队列实现栈
class MyStack {
public:
queue<int> que1;
queue<int> que2;
MyStack() {
}
void push(int x) {
que1.push(x);
}
int pop() {
int size = que1.size();
size--;
while(size--){
que2.push(que1.front());
que1.pop();
}
int res = que1.front();
que1.pop();
que1 = que2;
while(!que2.empty()){
que2.pop();
}
return res;
}
int top() {
return que1.back();
}
bool empty() {
return que1.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
收获
今天呐,主要就是栈实现队列和队列实现栈,栈实现队列时的思想很重要,输出栈空的时候把输入栈的元素都入栈进来