队列和栈

来源:互联网 发布:淘宝订单没有代付选项 编辑:程序博客网 时间:2024/06/18 07:34

使用标准库的栈和队列时,先包含相关的头文件

#include<stack>

#include<queue>

定义栈如下:

stack<int> stk;

定义队列如下:

queue<int> q;

栈提供了如下的操作

[cpp] view plain copy
  1. s.empty()               如果栈为空返回true,否则返回false  
  2. s.size()                返回栈中元素的个数  
  3. s.pop()                 删除栈顶元素但不返回其值  
  4. s.top()                 返回栈顶的元素,但不删除该元素  
  5. s.push()                在栈顶压入新元素  


队列提供了下面的操作

[cpp] view plain copy
  1. q.empty()               如果队列为空返回true,否则返回false  
  2. q.size()                返回队列中元素的个数  
  3. q.pop()                 删除队列首元素但不返回其值  
  4. q.front()               返回队首元素的值,但不删除该元素  
  5. q.push()                在队尾压入新元素  
  6. q.back()                返回队列尾元素的值,但不删除该元素  

#include<cstdio>
#include<stack>//
 
#include<queue>//队列 
#include<algorithm>
using namespace std;
int main()
{
stack<int >sta;
int a,b,d,c,e,f;
a=2;b=1;c=3;
sta.push(a);//进栈 a
sta.push(b);//     b
sta.push(c);
d=sta.top();//出栈 c 3   逆序出栈 
sta.pop();//删除栈顶元素 c 3 
printf("%d\n",d);//输出栈顶元素b 1
e=sta.top();
sta.pop();//删除栈顶元素 b 1 
printf("%d\n",e); 
if(!sta.empty()) //判断栈中是否为空 
    f=sta.top();//不为空,则输出栈中下一个元素a 2
    printf("%d\n",f);
return 0;
}
输出结果为3 1 2

#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>//队列
using namespace std;
int main()
{
queue<int >que;
int a=5,b=4,c=3,d=2,e=1;
que.push(a);//入列
que.push(b);
que.push(c);
que.push(d);
que.push(e);
while(!que.empty())//顺序输出 
{
printf("%d\n",que.front());//输出最前面的数 
que.pop();//删除最前面的数
}
return 0;
}输出结果为5 4 3 2 1

优先队列
#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
using namespace std;
struct node
{
int you,ge;
bool friend operator<(node x,node y)//不能改变 只能是<
{
return x.you>y.you;
}
};
int main()
{
priority_queue<node>que;
struct node a,b,c;
a.ge=1;a.you=5;
     b.ge=2;b.you=4;
     c.ge=3;c.you=3;
     que.push(a);//入列 
     que.push(b);
     que.push(c);
     while(!que.empty())
     {
     printf("%d\n",que.top().you);//按优先级输出 
que.pop();
}
return 0;
 } 
输出结果为3 4 5
0 0
原创粉丝点击