简介

栈的特点

栈是C++中很常用的一种线性数据结构,定义在头文件<stack>中,具有如下特点:

基本操作

具体实现

这里,我们主要讲述一下如何使用STL实现栈。

系统类型:

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

int main()
{
	stack<int> s;
	s.push(1);
	s.push(5);
	s.push(7);
	
	cout << s.size() << endl;
	while(!s.empty())
	{
		cout << s.top() << " ";
		s.pop();
	}
	
	return 0;
}

输出:

3
7 5 1

自定义类型:

自定义类型也是很简单的:

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

struct node
{
	int val;
	node(int _v): val(_v) {}
};

int main()
{
	stack<node> s;
	s.push(node(1));
	s.push(node(5));
	s.push(node(7));
	
	cout << s.size() << endl;

	while(!s.empty())
	{
		cout << (s.top()).val << " ";
		s.pop();
	}
	
	return 0;
}

输出同上。