在C++標(biāo)準(zhǔn)庫(kù)(STL)中,實(shí)現(xiàn)了棧和隊(duì)列,方便使用,并提供了若干方法。以下作簡(jiǎn)要介紹。
1. 棧(stack)說(shuō)明及舉例:
使用棧,要先包含頭文件 : #include<stack>
定義棧,以如下形式實(shí)現(xiàn): stack<Type> s; 其中Type為數(shù)據(jù)類型(如 int,float,char等)。
棧的主要操作:
s.push(item); //將item壓入棧頂
s.pop(); //刪除棧頂?shù)脑?,但不?huì)返回
s.top(); //返回棧頂?shù)脑兀粫?huì)刪除
s.size(); //返回棧中元素的個(gè)數(shù)
s.empty(); //檢查棧是否為空,如果為空返回true,否則返回false
//棧操作舉例:
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
void 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()<<" numbers.They are:"<<endl;
while(!s.empty())
{
cout<<s.top()<<" ";
s.pop();
}
cout<<"\nNow the size is "<<s.size()<<endl;
system("Pause");
}
結(jié)果截圖:

2、隊(duì)列(queue)說(shuō)明及舉例:
使用隊(duì)列,要先包含頭文件 : #include<queue>
定義隊(duì)列,以如下形式實(shí)現(xiàn): queue<Type> q; 其中Type為數(shù)據(jù)類型(如 int,float,char等)。
隊(duì)列的主要操作:
q.push(item) //將item壓入隊(duì)列尾部
q.pop() //刪除隊(duì)首元素,但不返回
q.front() //返回隊(duì)首元素,但不刪除
q.back() //返回隊(duì)尾元素,但不刪除
q.size() //返回隊(duì)列中元素的個(gè)數(shù)
q.empty() //檢查隊(duì)列是否為空,如果為空返回true,否則返回false
//隊(duì)列操作舉例
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
void 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()<<" numbers."<<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<<"Now the Queue has "<<q.size()<<" numbers."<<endl;
system("Pause");
}
結(jié)果截圖:

轉(zhuǎn)載自:https://blog.csdn.net/livecoldsun/article/details/25011413