当前位置: 首页> 房产> 市场 > 栈与队列,优先队列与双端队列(C++)

栈与队列,优先队列与双端队列(C++)

时间:2025/7/12 6:13:58来源:https://blog.csdn.net/z202331720425/article/details/141790733 浏览次数:0次

在C语言阶段,我们学过两种数据结构,栈与队列,一种是先进后出,一种是先进先出。

在C++阶段,我们有新容器来方便快捷的使用栈和队列而不需要我们手动来编写

即stack与queue

我们直接来看对应接口

stack

同时放上对应的习题

最小栈

. - 力扣(LeetCode)

class MinStack
{
public: void push(int x){ // 只要是压栈,先将元素保存到_elem中_elem.push(x);// 如果x小于_min中栈顶的元素,将x再压入_min中if(_min.empty() || x <= _min.top())_min.push(x);}void pop(){// 如果_min栈顶的元素等于出栈的元素,_min顶的元素要移除if(_min.top() == _elem.top())_min.pop();_elem.pop();}int top(){return _elem.top();}int getMin(){return _min.top();}private:// 保存栈中的元素std::stack<int> _elem;// 保存栈的最小值std::stack<int> _min;
};

栈的压入、弹出序列

栈的压入、弹出序列_牛客题霸_牛客网

class Solution {
public:bool IsPopOrder(vector<int> pushV,vector<int> popV) {//入栈和出栈的元素个数必须相同if(pushV.size() != popV.size())return false;// 用s来模拟入栈与出栈的过程int outIdx = 0;int inIdx = 0;stack<int> s;while(outIdx < popV.size()){// 如果s是空,或者栈顶元素与出栈的元素不相等,就入栈while(s.empty() || s.top() != popV[outIdx]){if(inIdx < pushV.size())s.push(pushV[inIdx++]);elsereturn false;}// 栈顶元素与出栈的元素相等,出栈s.pop();outIdx++;}return true;}
};

逆波兰表达式求值

. - 力扣(LeetCode)

class Solution {
public:int evalRPN(vector<string>& tokens) {stack<int> s;for (size_t i = 0; i < tokens.size(); ++i){string& str = tokens[i];// str为数字if (!("+" == str || "-" == str || "*" == str || "/" == str)){s.push(atoi(str.c_str()));}else{// str为操作符int right = s.top();
s.pop();int left = s.top();s.pop();switch (str[0]){case '+':s.push(left + right);break;case '-':s.push(left - right);break;case '*':s.push(left * right);break;case '/':// 题目说明了不存在除数为0的情况s.push(left / right);break;}}}return s.top();}
};

queue

priority_queue的介绍和使用

优先队列是一种特殊的容器,他的最上层始终为最大(小)的元素,和堆非常类似

优先级队列默认使用vector作为其底层存储数据的容器,在vector上又使用了堆算法将vector中元素构造成 堆的结构,因此priority_queue就是堆,所有需要用到堆的位置,都可以考虑使用priority_queue。

注意: 默认情况下priority_queue是大堆

模拟实现

#include<iostream>
#include<vector>
#include<functional>
using namespace std;
template<class T>
class vectorless {
public:bool operator()(T a1, T a2) {return a1 < a2;}
};
template<class T>
class vectorgreater {
public:bool operator()(T a1, T a2) {return a1 > a2;}
};
namespace bit
{template <class T, class Container = vector<T>, class Compare = less<T> >class priority_queue{public:priority_queue() = default;template <class InputIterator>priority_queue(InputIterator first, InputIterator last) {while (first != last) {push(*first);++first;}}bool empty() const {return c.empty();}size_t size() const {return c.size();}T& top() {return c.front();}void adjustdown(int pos) {int child = pos * 2 + 1;Compare cmp;while (child < c.size()) {if (child + 1 < c.size() && cmp(c[child] , c[child + 1]))++child;if (cmp(c[pos] , c[child]))swap(c[pos], c[child]);elsebreak;pos = child;child = child * 2 + 1;}}void adjustup(int pos) {Compare cmp;int parent = (pos - 1) / 2;while (parent >= 0) {if (cmp(c[parent] , c[pos]))swap(c[parent], c[pos]);elsebreak;pos = parent;parent = (pos - 1) / 2;}}void push(const T& x) {c.push_back(x);adjustdown(0);}void pop() {swap(c[0], c[size() - 1]);c.pop_back();adjustdown(0);}private:Container c;Compare comp;};
};

其中compare为仿函数,我们可以通过传递对应的仿函数来支持其他类的比较,或者也可以在类中写上对应的运算符重载

class Date
{
public:Date(int year = 1900, int month = 1, int day = 1): _year(year), _month(month), _day(day){}bool operator<(const Date& d)const{return (_year < d._year) ||(_year == d._year && _month < d._month) ||(_year == d._year && _month == d._month && _day < d._day);}bool operator>(const Date& d)const{return (_year > d._year) ||(_year == d._year && _month > d._month) ||(_year == d._year && _month == d._month && _day > d._day);}friend ostream& operator<<(ostream& _cout, const Date& d){_cout << d._year << "-" << d._month << "-" << d._day;return _cout;}private:int _year;int _month;int _day;
};void TestPriorityQueue()
{// 大堆,需要用户在自定义类型中提供<的重载priority_queue<Date> q1;q1.push(Date(2018, 10, 29));q1.push(Date(2018, 10, 28));q1.push(Date(2018, 10, 30));cout << q1.top() << endl;// 如果要创建小堆,需要用户提供>的重载priority_queue<Date, vector<Date>, greater<Date>> q2;q2.push(Date(2018, 10, 29));q2.push(Date(2018, 10, 28));q2.push(Date(2018, 10, 30));cout << q2.top() << endl;
}

数组中第k大的元素

. - 力扣(LeetCode)

class Solution {
public:int findKthLargest(vector<int>& nums, int k) {// 将数组中的元素先放入优先级队列中priority_queue<int> p(nums.begin(), nums.end());// 将优先级队列中前k-1个元素删除掉for(int i= 0; i < k-1; ++i){p.pop();}return p.top();}
};

适配器

适配器是一种设计模式(设计模式是一套被反复使用的、多数人知晓的、经过分类编目的、代码设计经验的总 结),该种模式是将一个类的接口转换成客户希望的另外一个接口。

STL标准库中stack和queue的底层结构

虽然stack和queue中也可以存放元素,但在STL中并没有将其划分在容器的行列,而是将其称为容器适配 器,这是因为stack和队列只是对其他容器的接口进行了包装,STL中stack和queue默认使用deque

deque的简单介绍(了解)

deque的原理介绍

deque(双端队列):是一种双开口的"连续"空间的数据结构,双开口的含义是:可以在头尾两端进行插入和 删除操作,且时间复杂度为O(1),与vector比较,头插效率高,不需要搬移元素;与list比较,空间利用率比较高。

deque并不是真正连续的空间,而是由一段段连续的小空间拼接而成的,实际deque类似于一个动态的二维 数组,其底层结构如下图所示:

双端队列底层是一段假象的连续空间,实际是分段连续的,为了维护其“整体连续”以及随机访问的假象,落 在了deque的迭代器身上,因此deque的迭代器设计就比较复杂

那deque是如何借助其迭代器维护其假想连续的结构呢?

deque的缺陷

与vector比较,deque的优势是:头部插入和删除时,不需要搬移元素,效率特别高,而且在扩容时,也不 需要搬移大量的元素,因此其效率是必vector高的。

与list比较,其底层是连续空间,空间利用率比较高,不需要存储额外字段。

但是,deque有一个致命缺陷:不适合遍历,因为在遍历时,deque的迭代器要频繁的去检测其是否移动到 某段小空间的边界,导致效率低下,而序列式场景中,可能需要经常遍历,因此在实际中,需要线性结构时,大多数情况下优先考虑vector和list,deque的应用并不多,而目前能看到的一个应用就是,STL用其作 为stack和queue的底层数据结构。

为什么选择deque作为stack和queue的底层默认容器

stack是一种后进先出的特殊线性数据结构,因此只要具有push_back()和pop_back()操作的线性结构,都可 以作为stack的底层容器,比如vector和list都可以;queue是先进先出的特殊线性数据结构,只要具有 push_back和pop_front操作的线性结构,都可以作为queue的底层容器,比如list。但是STL中对stack和 queue默认选择deque作为其底层容器,主要是因为:

1. stack和queue不需要遍历(因此stack和queue没有迭代器),只需要在固定的一端或者两端进行操作。

2. 在stack中元素增长时,deque比vector的效率高(扩容时不需要搬移大量数据);queue中的元素增长 时,deque不仅效率高,而且内存使用率高。

结合了deque的优点,而完美的避开了其缺陷。

关键字:栈与队列,优先队列与双端队列(C++)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: