stack容器和queue容器

stack容器和queue容器,第1张

stack容器和queue容器

stack是一个先进后出的数据结构
栈只有顶端元素才可以被外界使用
因此栈不允许有遍历行为 

#include
#include
using namespace std;
void test()
{
	stacks;
	s.push(1);
	s.push(2);
	s.push(3);
	s.push(4);
	s.push(5);
	cout << "栈的大小为:" << s.size() << endl;
	while(!s.empty())
	{
		cout << "栈顶元素为:" << s.top() << "  ";
		s.pop();
		cout << "栈的大小为:" << s.size() << endl;
	}
	s.push(888);
	cout << "栈顶元素为:" << s.top() << "  ";
	cout << "栈的大小为:" << s.size() << endl;
}
int main()
{
	test();
	return 0; 
}

queue是一种先进先出的数据接口
队列容器允许从一端新增元素,从另一端移除元素
队列只有队头和队尾可以被外界使用,因此队列不允许有遍历行为  

#include
#include 
using namespace std;
void test()
{
	queueq;
	for(int i = 0;i < 5;i++)
	{
		q.push(i);
	}
	while(!q.empty())
	{
		cout << "第一个元素:" << q.front() << endl;
		cout << "最后一个元素:" << q.back() << endl;
		cout << "栈的大小为:" << q.size() << endl;
		//移除队头元素
		q.pop();
		cout << "移除队头元素后队头元素为:" << q.front() << endl; 
		cout << "移除队头元素后栈的大小为:" << q.size() << endl;
		cout << endl;
	}
	//将移除元素后的栈q拷贝给q1
	queueq1(q); 
	cout << "移除后:" << endl; 
	if(q1.empty())
	{
		cout << "栈q1为空!" << endl;
	}
	else
	{
		cout << "栈不为空!" << endl;
		cout << "第一个元素:" << q.front() << endl;
		cout << "最后一个元素:" << q.back() << endl;
		cout << "栈的大小为:" << q.size() << endl; 
	} 
}
int main()
{
	test();
	return 0; 
} 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5702905.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存