C++第八讲:STL--stack和queue的使用及模拟实现
1.stack的使用
有了前面的基础之后,栈和队列的使用都很简单,而且其中的接口我们在数据结构中都实现过,所以我们直接看一遍即可:
不同的是,栈中没有实现迭代器,这其实与栈和队列的实现有关:
那么它的访问方式只有循环出栈和获取栈顶元素:
#include <stack>
int main()
{
stack<string> s1;
s1.emplace("hello world!");
s1.emplace("Xxxxxxxxxxxxx");
while (!s1.empty())
{
cout << s1.top();
s1.pop();
}
cout << endl;//Xxxxxxxxxxxxxhello world!
cout << s1.empty() << endl;//1,表示此时栈为空
return 0;
}
2.queue的使用
queue的使用和stack相同,这里不再看:
#include <queue>
int main()
{
queue<string> q1;
q1.emplace("hello world!");
q1.emplace("Xxxxxxxxxxxx");
while (!q1.empty())
{
cout << q1.front();
q1.pop();
}
cout << endl;//hello world!Xxxxxxxxxxxx
cout << q1.empty() << endl;//1,表示队列为空
return 0;
}
3.栈和队列OJ题
3.1题目1:最小栈
链接: 最小栈
class MinStack {
public:
MinStack() {
//初始化堆栈操作其实不用实现:
//1.自己不实现,内置类型:不一定处理,自定义类型:走自己的构造函数,stack中有自己的构造函数
//2.写了函数不实现:走初始化列表,没有初始化列表,判断是否给了初始值,最后走构造函数
//所以我们既可以给这个函数删了,也可以置之不管,我们这里直接不管
}
void push(int val) {
_stack.push(val);
if(_minstack.empty() || val <= _minstack.top()) _minstack.push(val);
}
void pop() {
if(_stack.top() == _minstack.top()) _minstack.pop();
_stack.pop();
}
int top() {
return _stack.top();
}
int getMin() {
return _minstack.top();
}
private:
//创建两个栈
stack<int> _stack;
stack<int> _minstack;
};
3.2题目2:栈的压入、弹出序列
链接: 栈的压入、弹出序列
class Solution {
public:
bool IsPopOrder(vector<int>& pushV, vector<int>& popV) {
if(pushV.size() != popV.size()) return false;
stack<int> _stack;
int pushi = 0, popi = 0;
while(pushi < pushV.size())
{
_stack.push(pushV[pushi++]);//先入栈
while(!_stack.empty() && _stack.top() == popV[popi])
{
//当栈顶元素和要删除的元素相等时,要出栈
_stack.pop();
popi++;
}
}
return _stack.empty();//如果为空,返回true,否则返回false
}
};
3.3题目3:逆波兰表达式求值
链接: 逆波兰表达式求值
class Solution {
public:
int evalRPN(vector<string>& tokens) {
//首先要先取值入栈
stack<int> s1;
for(int i = 0; i