簡單順序棧(C++模版技術實現)

來源:互聯網
上載者:User

下面代碼僅供本人複習資料結構所用,實用性N低,各位飄過吧~~哈哈:>

//// C++ 模版技術實現簡單順序棧. // #include <cstdlib>#include <iostream>#include <iomanip>#include <stdexcept>//// 順序棧類模版.  //template <typename T>class Stack{private:int _top;size_t _size;T *_pStack;static const size_t _DEF_SIZE = 20;// // _MIN_TOP 不應為 size_t 類型.// 因為 size_t 類型與 int 類型變數比較時會將 int 類型轉換為 size_t 類型. //static const int _MIX_TOP = 0; public:Stack(const size_t size = _DEF_SIZE): _top(_MIX_TOP - 1), _size(size){ _pStack = new T[_size]; }~Stack(void){ delete[] _pStack; }bool isEmpty(void) const{ return _MIX_TOP > _top; }bool isFull(void) const{ return _size - 1 == _top; }T getTop(void) const{if (isEmpty()) {throw std::underflow_error("棧空下溢 !"); }return _pStack[_top]; }void push(const T &val){if (isFull()) {throw std::overflow_error("棧滿上溢 !");}_pStack[++_top] = val;}T pop(void){ if (isEmpty()) {throw std::underflow_error("棧空下溢 !");}return _pStack[_top--];}};//// 測試棧. // int main(void){const size_t MAX_SIZE = 20;Stack<int> stack(MAX_SIZE);std::cout << "棧" << (stack.isEmpty() ? "" : "不") << "為空白." << std::endl; std::cout << "棧" << (stack.isFull() ? "" : "不") << "為滿." << std::endl; for (size_t i = 0; i < MAX_SIZE; ++i){stack.push(i);std::cout << std::setw(3) << stack.getTop();}// stack.push(MAX_SIZE);std::cout << std::endl;std::cout << "棧" << (stack.isEmpty() ? "" : "不") << "為空白." << std::endl; std::cout << "棧" << (stack.isFull() ? "" : "不") << "為滿." << std::endl; for (size_t i = 0; i < MAX_SIZE; ++i){std::cout << std::setw(3) << stack.pop();}// std::cout << std::setw(3) << stack.pop();return EXIT_SUCCESS;}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.