今日任务:
* 理论基础
* 232.用栈实现队列
* 225. 用队列实现栈
理论基础了解一下 栈与队列的内部实现机智,文中是以C++为例讲解的。文章讲解:https://programmercarl.com/%E6%A0%88%E4%B8%8E%E9%98%9F%E5%88%97%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html232.用栈实现队列大家可以先看视频,了解一下模拟的过程,然后写代码会轻松很多。题目链接/文章讲解/视频讲解:https://programmercarl.com/0232.%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97.html225. 用队列实现栈可以大家惯性思维,以为还要两个队列来模拟栈,其实只用一个队列就可以模拟栈了。建议大家掌握一个队列的方法,更简单一些,可以先看视频讲解题目链接/文章讲解/视频讲解:https://programmercarl.com/0225.%E7%94%A8%E9%98%9F%E5%88%97%E5%AE%9E%E7%8E%B0%E6%A0%88.html
class MyQueue {
stack<int> inputStack;
stack<int> outputStack;
public:
MyQueue() {
}
void push(int x) {
inputStack.push(x);
}
int pop() {
if (outputStack.empty()) {
while (!inputStack.empty()) {
outputStack.push(inputStack.top());
inputStack.pop();
}
}
int result = outputStack.top();
outputStack.pop();
return result;
}
int peek() {
if (outputStack.empty()) {
while (!inputStack.empty()) {
outputStack.push(inputStack.top());
inputStack.pop();
}
}
return outputStack.top();
}
bool empty() {
return inputStack.empty() && outputStack.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();
*/
class MyStack {
queue<int> que;
public:
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size();
for (int i = 0; i < size - 1; ++ i) {
que.push(que.front());
que.pop();
}
int result = que.front();
que.pop();
return result;
}
int top() {
int result = pop();
que.push(result);
return result;
}
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();
*/