stack和queue

发布于:2025-04-06 ⋅ 阅读:(18) ⋅ 点赞:(0)

1.stack的使用

函数说明 接口说明

stack()

构造空的栈

empty

检测stack是否为空

size

返回stack中元素的个数

top

返回栈顶元素的引用

push

将元素val压入stack中

pop

将stack中尾部的元素弹出
void test_stack()
{
	stack<int> st;
	st.push(1);
	st.push(2);
	st.push(3);
	st.push(4);
	
	while (!st.empty())
	{
		cout << st.top() << " ";
		st.pop();
	}
	cout << endl;
}

1.1 最小栈

155. 最小栈 - 力扣(LeetCode)

思路:创建两个栈,一个存最小值(最小栈),一个正常存值,当插入的数据小于等于最小栈的栈顶,就说明有新小的数据,插入最小栈中。删除时最小栈栈顶与正常栈栈顶相等时,最小栈栈顶值出栈。

class MinStack 
{
    public:
        MinStack() 
        {}
        
        void push(int val) 
        {
            if(_minst.empty() || val <= _minst.top())
            {
                _minst.push(val);
            }
            _st.push(val);
        }
        
        void pop() 
        {
            if(_minst.top() == _st.top())
            {
                _minst.pop();
            }
            _st.pop();
        }
        
        int top() 
        {
            return _st.top();
        }
        
        int getMin() 
        {
            return _minst.top();
        }

    private:
        stack<int> _st;
        stack<int> _minst;
};

1.2 栈的压入,弹出序列

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

1.入栈序列入栈一个值

2.栈顶数据跟出栈序列是否匹配,匹配则持续出栈

3.入栈序列结束,就结束了

最后判断栈中是否为空

bool IsPopOrder(vector<int>& pushV, vector<int>& popV) 
    {
        stack<int> st;
        int popi = 0;

        for(auto &e : pushV)
        {
            st.push(e);
            while(!st.empty() && st.top() == popV[popi])
            {
                st.pop();
                popi++;
            }    
        }
        return st.empty();
    }

2.queue的使用

函数声明 接口说明
queue::queue - C++ Reference 构造空的队列

empty

判断队列是否为空

size

返回队列中的有效元素的个数

front

返回队头元素的引用

back

返回队尾元素的引用

push

在队尾插入值为val的值

pop

队头元素出队列
void test_queue()
{
    queue<int> q;
    q.push(1);
    q.push(2);
    q.push(3);
    q.push(4);
    q.push(5);
    cout << q.size() << endl;
    while (!q.empty())
    {
        cout << q.front() << " ";
        q.pop();
    }
    cout << endl;
}

2.1二叉树的层序遍历

102. 二叉树的层序遍历 - 力扣(LeetCode)

思路:创建一个装有树节点的队列,右levelsize来记录节点的层数,控制当前层数个数,一层一层出。

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) 
    {
        vector<vector<int>> vv;
        int levelSize = 0;
        queue<TreeNode*> q;
        if(root)
        {
            q.push(root);
            levelSize = 1;
        }
        while(!q.empty())
        {
            vector<int> v;
            while(levelSize--)
            {
                TreeNode* front = q.front();
                v.push_back(front->val);
                q.pop();
                if(front->left)
                    q.push(front->left);

                if(front->right)
                    q.push(front->right);
            }
            levelSize = q.size();
            vv.push_back(v);
        }
        return vv;
    }
};

3.容器适配器

3.1什么是容器适配器

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

容器适配器就像我们的电源适配器一样。是一种转化接口,把一种接口转化为我们需要的接口。

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

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

4.deque的介绍

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

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

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

deque是由一个指针数组(中控数组)来控制数据存储的数组。

中控数组的每一个节点指向一个buffer的空间,迭代器的node指向当前节点,first指向当前buffer的起始位置,last指向当前buffer的结束位置,cur在buffer中移动。

4.1 deque的缺陷

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

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

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

stack是一种后进先出的数据结构,因此只要具备push_back和pop_back操作的线性结构,都可以作为stack的底层容器,比如vectorlist都可以;

queue是先进先出的特殊线性数据结构,只要具有push_backpop_front操作的线性结构,都可以作为queue的底层容器,比如list

但是STL中对stackqueue默认选择deque作为其底层容器,主要是因为:

  1. stack和queue不需要遍历(stack和queue没有迭代器),只需要固定在一端操作或者两端操作。
  2. 在stack中元素增长时,deque比vector的效率高(扩容时不需要移动大量数据)

结合queue的优点,而完美的避开缺陷。

4.3 对stack和queue的模拟实现

对stack的模拟实现

namespace wxw
{
	template<class T, class Container = deque<T>>
	class stack
	{
	public:
		stack()
		{}

		void push(const T& x)
		{
			_con.push_back(x);
		}
		void pop()
		{
			_con.pop_back();
		}

		bool empty() const
		{
			return _con.empty();
		}

		size_t size() const
		{
			return _con.size();
		}

		T& top()
		{
			return _con.back();
		}

		const T& top() const
		{
			return _con.back();
		}
	private:
		Container _con;
	};
}

对queue的模拟实现

#pragma once
namespace wxw
{
	template<class T, class Containter = deque<T>>
	class queue
	{
	public:
		queue()
		{}
		void push(const T& x)
		{
			_con.push_back(x);
		}
		void pop()
		{
			_con.pop_front();
		}

		bool empty()
		{
			return _con.empty();
		}

		size_t size()
		{
			return _con.size();
		}

		T& front()
		{
			return _con.front();
		}

		const T& front() const
		{
			return _con.front();
		}

		T& back()
		{
			return _con.back();
		}

		const T& back() const
		{
			return _con.back();
		}
	private:
		Containter _con;
	};
}

5.priority_queue的介绍和使用

5.1 priority_queue的使用

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

函数声明 接口说明
priority_queue::priority_queue - C++ Reference 构造一个空的优先级队列

empty

检测优先级队列是否为空

top

返回优先级队列中最大(最小)的元素

push

在优先级队列中插入x

pop

删除优先级队列中最大(最小的元素),即堆顶元素
int main()
{
	vector<int> v = { 6,4, 7,3,9,1,2,8 };
	priority_queue<int> q(v.begin(),v.end());//大堆

	cout << q.top() << endl;

	priority_queue<int, vector<int>, greater<int>> pq(v.begin(), v.end());//小堆
	cout << pq.top() << endl;


	return 0;
}

如果在priority_queue中放自定义类型的数据,用户需要在自定义类型中提供" < "或者" > "的重载。

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;
}

5.2 priority_queue的模拟实现

#pragma once

namespace wxw
{

	template<class T, class Containter = vector<T>>
	class priority_queue
	{
	public:
		void adjustUp(size_t child)
		{
			size_t parent = (child - 1) / 2;
			while (child > 0)
			{
				if (_con[parent] < _con[child])
				{
					swap(_con[parent], _con[child]);
					child = parent;
					parent = (child - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}
		void push(const T& x)
		{
			_con.push_back(x);
			adjustUp(_con.size() - 1);
		}

		void adjustDown(size_t parant)
		{
			size_t child = parant * 2 + 1;
			
			while (child < _con.size())
			{
				if (child + 1 < _con.size() && _con[child] < _con[child + 1])
				{
					child++;
				}

				if (_con[parant] < _con[child])
				{
					swap(_con[parant], _con[child]);
					parant = child;
					child = parant * 2 + 1;
				}
				else
				{
					break;
				}
			}
		}

		void pop()
		{
			swap(_con.front(), _con.back());
			_con.pop_back();
			adjustDown(0);
		}

		const T& top()
		{
			return _con[0];
		}

		bool empty() const
		{
			return _con.empty();
		}

		size_t size() const
		{
			return _con.size();
		}

	private:
		Containter _con;
	};
}

5.3仿函数

上述给了优先级队列的模拟实现,那么我们应该怎么调整大小堆呢?这样就用到了仿函数,仿函数是一个类。

template<class T>
	class Less
	{
	public:
		bool operator()(const T& x, const T& y)
		{
			return x < y;
		}
	};

仿函数没有类对象,重载了operator()。

修改过后的priority_queue的代码

template<class T>
	class Less
	{
	public:
		bool operator()(const T& x, const T& y)
		{
			return x < y;
		}
	};

	template<class T>
	class Greater
	{
	public:
		bool operator()(const T& x, const T& y)
		{
			return x > y;
		}
	};

	template<class T, class Containter = vector<T>, class Compare = Less<T>>
	class priority_queue
	{
	public:
		void adjustUp(size_t child)
		{
			Compare com;
			size_t parent = (child - 1) / 2;
			while (child > 0)
			{
				//if (_con[parent] < _con[child])
				if (com(_con[parent], _con[child]))
				{
					swap(_con[parent], _con[child]);
					child = parent;
					parent = (child - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}
		void push(const T& x)
		{
			_con.push_back(x);
			adjustUp(_con.size() - 1);
		}

		void adjustDown(size_t parent)
		{
			size_t child = parent * 2 + 1;
			Compare com;
			while (child < _con.size())
			{
				if (child + 1 < _con.size() && com(_con[child], _con[child + 1]))
				{
					child++;
				}

				//if (_con[parent] < _con[child])
				if (com(_con[parent], _con[child]))
				{
					swap(_con[parent], _con[child]);
					parent = child;
					child = parent * 2 + 1;
				}
				else
				{
					break;
				}
			}
		}

		void pop()
		{
			swap(_con.front(), _con.back());
			_con.pop_back();
			adjustDown(0);
		}