stl_stack_queue的使用及OJ题

本文介绍了如何在C++中使用STL的stack和queue容器,并提供了两个编程练习题目,一个是设计一个支持快速检索最小元素的MinStack,另一个是检查给定的压入和弹出序列是否合法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

stl_stack_queue的使用及OJ题

stl_stack_queue的使用

#include <iostream>
#include <stack>
#include <queue>
using namespace std;

void test_stack()
{
	stack<int> st;
	st.push(1);
	st.push(2);
	st.push(3);
	st.push(4);
	st.push(5);

	while (!st.empty())
	{
		cout << st.top() << endl;
		st.pop();
	}

}

void test_queue()
{
	queue<int> q;
	q.push(1);
	q.push(2);
	q.push(3);
	q.push(4);
	q.push(5);

	while (!q.empty())
	{
		cout << q.front() << endl;
		q.pop();
	}

}

int main()
{
	test_stack();
	cout << endl;
	test_queue();

	return 0;
}

相关OJ题

// stack 与 queue的 OJ题
//
T1. 最小栈
设计一个支持 push , pop , top 操作,并能在常数时间内检索到最小元素的栈。
实现 MinStack 类:
  MinStack() 初始化堆栈对象。
  void push(int val) 将元素val推入堆栈
  void pop()  删除堆栈顶部的元素
  int top()  获取堆栈顶部的元素
  int getMin()  获取堆栈中的最小元素

class MinStack
{
public:
	MinStack() //当初始化列表为空时,自定义类型成员变量会去调用自身类的构造函数;而内置类型成员变量不做任何处理。
	{}

	void push(int val)
	{
		_st.push(val);

		if (_minst.empty() || val<=_minst.top()) 
			_minst.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 实现一个 MinStack 
	stack<int> _st;    //普通栈  
	stack<int> _minst; //最小栈  //用来记录数据的最小值
};




//T2.栈的压入、弹出序列 (栈 模拟这个过程)
//描述:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。
// 假设压入栈的所有数字均不相等。例如序列 1,2,3,4,5 是某栈的压入顺序,序列 4,5,3,2,1 是该压栈序列对应的一个弹出序列,但 4,3,5,1,2
// 就不可能是该压栈序列的弹出序列。

class Solution
{
public:
	bool IsPopOrder(vector<int> pushV,vector<int> popV)
	{
		stack<int> st;
		int popi = 0;
		for (auto pushVal : pushV)
		{
			st.push(pushVal);

			//出栈序列匹配后要持续比较,可能会有多个匹配
			while (!st.empty() && popV[popi]==st.top())
			{
				++popi;
				st.pop();
			}
		}

		// return popi==popV.size();
		return st.empty();

	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值