C++ STl队列、栈应用

来源:互联网 发布:linux压缩文件命令 编辑:程序博客网 时间:2024/06/10 15:28

C++ STL Stack、Queue(堆栈、队列) 用函数实现了一个(FILO&FIFO)的数据结构。

也就是说我们可以用函数直接代替队列和栈的的操作,省时省力省脑省空间。

c++ 栈stack的成员函数介绍

操作比较和分配堆栈

empty()堆栈为空则返回真

pop()移除栈顶元素

push()在栈顶增加元素

size()返回栈中元素数目

top()返回栈顶元素

C++队列Queue类成员函数如下:

back()返回最后一个元素

empty()如果队列空则返回真

front()返回第一个元素

pop()删除第一个元素

push()在末尾加入一个元素

size()返回队列中元素的个数

元素类是必须声明的,如:

queue<int>q1;

queue<double>q2;

stack<int>s1;

stack<string>s2;

应用举例:邻接矩阵中的搜索。

#include<cmath>#include<cstdio>#include<queue>#include<stack>#include<string>#include<cstring>#include<iostream>#include<algorithm>using namespace std;queue<int>q; stack<int>s;//声明 int g[200][200],hash[2000],n;//非递归DFS void dfs(){memset(hash,0,sizeof hash);cout << 1;hash[1]=1;s.push(1);//栈初始化 while (!s.empty()){int top=s.top();for (int i=1;i<=n;i++) {if (g[top][i]==1&&hash[i]==0) {cout<< ' ' << i;hash[i]=1;s.push(i);break;//DFS,找到一个节点就继续向下扩展。 }}if (top==s.top()) s.pop();//如果栈中没用压入新元素(即没有可扩展的节点),就弹出栈顶元素。 }cout<<endl;}void bfs(){memset(hash,0,sizeof hash);cout << 1;q.push(1);hash[1]=1;while (!q.empty()){for (int i=1;i<=n;i++) if (g[q.front()][i]==1&&hash[i]==0) {cout<< ' ' << i;hash[i]=1;q.push(i);}q.pop();}cout<<endl;}int main(){cin >> n ;memset(g,0,sizeof g);for (int i=1;i<=n;i++)for (int j=1;j<=n;j++) cin >> g[i][j];dfs();bfs();return 0;}




1 0
原创粉丝点击