栈与队列理论基础:
栈提供push 和 pop 等等接口,所有元素必须符合先进后出规则,所以栈不提供走访功能,也不提供迭代器(iterator)。 不像是set 或者map 提供迭代器iterator来遍历所有元素。
栈是以底层容器完成其所有的工作,对外提供统一的接口,底层容器是可插拔的(也就是说我们可以控制使用哪种容器来实现栈的功能)。
所以STL中栈往往不被归类为容器,而被归类为container adapter(容器适配器)。
LeetCode232.用栈实现队列
题目链接:232. 用栈实现队列 - 力扣(LeetCode)
思路:
两个栈一个进栈一个出栈来模拟队列的过程
class MyQueue {
public:
stack<int> in;
stack<int> out;
MyQueue() {
}
void push(int x) {
in.push(x);
}
int pop() {
//只有当out为空才从in调入数据
if(out.empty()) {
//从in导入数据给out
while(!in.empty()) {
out.push(in.top());//将in的进栈顺序颠倒过来进out
in.pop();
}
}
int result = out.top();
out.pop();
return result;
}
int peek() {
int res = this->pop();//直接调用pop函数
out.push(res);//pop弹出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();
*/
LeetCode225.用队列实现栈
题目链接:225. 用队列实现栈 - 力扣(LeetCode)
思路:
该题可以用一个队列模拟栈,只需要pop时把出的数再添加回队列即可
class MyStack {
public:
queue<int> in;
MyStack() {
}
void push(int x) {
in.push(x);
}
int pop() {
int num = in.size() - 1;
while(num--) {
in.push(in.front());//队列的front是出,back是入
in.pop();
}
int result = in.front();
in.pop();
return result;
}
int top() {
return in.back();
}
bool empty() {
return in.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();
*/