C++栈和队列

在C++标准库中,实现了栈和队列。以下简要说明:

1.栈(stack)说明与举例:

使用栈,要先包括头文件#include<stack>

定义栈,一下形式实现

stack<Type>s;其中Type为数据类型(如int ,char,float等)

栈的主要操作:

s.push(item);//将item压入栈顶
s.pop();//删除栈顶的元素,但是不会返回
s.top();//返回栈顶的元素,但是不会删除
s.size();//返回栈中元素的个数
s.empty();//检查栈是否为空,如果为空返回ture,否则返回false;

栈操作举例:

#include<iostream>
#include<stack>
#include<queue>
using namespace std;
int  main()
{
    stack <int> s;
    int num;
    cout<<"------Test for Stack-----"<<endl;
    cout<<"Input number:"<<endl;
    while(cin>>num)
    {
        s.push(num);
    }
    cout<<"The Stack has "<<s.size()<<" number.they are:"<<endl;
    while(!s.empty())
    {
        cout<<s.top()<<" ";
        s.pop();
    }
    cout<<"\nNow the size is "<<s.size()<<endl;
    //system("Pause");
}

输出:


2.队列(queue)说明及举例:

使用队列,要先包含头文件:#include<queue>

定义队列,以如下形式实现:queue<Type>q;其中Type为数据类型(如Int,float,char等)

队列的主要操作:

(此处修改下图q.front();//返回队头元素,但不删除)感谢评论区指出错误。

q.push(item)//将item压入队列尾部
q.pop();//删除队尾首元素,但不返回
q.front();//返回队尾元素,但不删除
q.back();//返回队尾元素,但不删除
q.size();//返回队列中元素的个数
q.empty();//检查队列是否为空,如果为空返回ture,否则返回false

队列操作举栗:

#include<iostream>
#include<stack>
#include<queue>
using namespace std;
int  main()
{
    queue<int>q;
    int num;
    cout<<"------Test for Queue-----"<<endl;
    cout<<"Input number:"<<endl;
    while(cin>>num)
    {
        q.push(num);
    }
    cout<<"Now the Queue has "<<q.size()<<" number."<<endl;
    cout<<"The first is "<<q.front()<<endl;
    cout<<"The last is "<<q.back()<<endl;
    cout<<"All numbers: "<<endl;
    while(!q.empty())
    {
        cout<<q.front()<<" ";
        q.pop();
    }
    cout<<"\nNow the Queue is "<<q.size()<<" number."<<endl;
    //system("Pause");
}

结果;

参考博客:https://blog.csdn.net/forward627/article/details/52314544   笔芯()

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值