棧的簡單實現——使用C++容器庫(STL Stack)

前言

作爲比較簡單的數據結構,使用C++容器庫中的棧(std::stack)也相對比較簡單。
在頭文件中,棧的定義爲:

template<
    class T,
    class Container = std::deque<T>
> class stack;

Stack

常用函數:

  • top():訪問棧頂
  • empty():判斷棧空
  • size():返回棧中元素數
  • push():向棧頂插入元素
  • pop():刪除棧頂元素

代碼

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <stack>
using namespace std;

int main()
{
  int n;
  while (cin>>n) {
    stack<int> s;
    string ch;
    int val;
    while (n--) {
      cin>>ch;
      if (ch == "PUSH") {
        cin>>val;
        s.push(val);
      } else if (ch == "POP") {
        if (!s.empty())
          s.pop();
      } else if (ch == "TOP") {
        if (!s.empty())
          cout<<"Top : "<<s.top()<<endl;
        else
          cout<<"Empty"<<endl;
      }
      cout<<"Size : "<<s.size()<<endl;
    }
    cout<<endl;
  }
}

測試結果

Stack

參考資料

http://zh.cppreference.com/w/cpp/container/stack

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