用棧所需頭文件:

# include <stack>

定義棧

stack<type> s; //type 意思是數據類型,可爲int,double等

實現棧的操作

1. s.push(num);        //()內填命名如num,將num壓入棧頂  
2. s.pop();            //刪除棧頂的元素,但不會返回  
3. s.top();            //返回棧頂的元素,但不會刪除  
4. s.size();           //返回棧中元素的個數  
5. s.empty();          //檢查棧是否爲空  

代碼

#include <iostream>
#include <stack>   //用棧所需造的頭文件
using namespace std;

int main()
{
    stack<int> s;  // 定義棧 其中"<>"內填類型 如:int,double等
    int a;

    cout << "輸入的數是:"<<endl;
    while(cin >>a)
    {
        s.push(a);
    }
    cout << "輸入的數字數目是:" <<s.size()<< endl << "輸出的數字是" << endl;
    while(!s.empty())
    {
        cout << s.top()<<" "; //輸出棧頂的數
        s.pop();              //刪除棧頂的數
    }
    cout << endl << "現在棧中的數字數目是:" <<s.size()<<endl;
    return 0;
}

加油 我相信你能看懂。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章