【資料結構】用C++編寫棧及基本操作(包括入棧,出棧,獲得棧頂,摧毀,清空等等)

來源:互聯網
上載者:User

標籤:棧   資料結構   操作   類模板   c++   

//【資料結構】用C++編寫棧及基本操作(包括入棧,出棧,獲得棧頂,摧毀,清空等等)//標頭檔#ifndef _SEQ_STACK_#define _SEQ_STACK_#include <iostream>using namespace std;template <class Type>class SeqStack{public:SeqStack(size_t sz=INIT_SIZE){capacity = sz > INIT_SIZE ? sz : INIT_SIZE;base = new Type[capacity];top = 0;}~SeqStack(){destory();}public:bool empty() const                  //判斷是否為空白{return(top == 0);}bool full()const                   //判斷是否已滿{return(top >= capacity);}void push(const Type &x)           //進棧{if (full() ){cout << "棧已滿,不能插入。" << endl;return;}base[top++] = x;}void pop()                         //出棧{top--;}bool getTop(Type &x) const        //獲得棧頂{if (top == 0)return false;x = base[top - 1];return true;}int length() const                //求大小{return top;}void clear()                     //清除{top = 0;}void destory()                   //摧毀{delete[]base;base = NULL;capacity = top = 0;}void show() const                //顯示{if (empty() == 1){cout << "棧為空白" << endl;return;}for (int i=top-1; i >=0; i--){cout << base[i]<<endl;}}private:enum {INIT_SIZE = 8 };Type *base;int capacity;int top;};#endif//主函數#include "SeqStack.h"void main(){SeqStack<int> mystack;int select = 1;int Item;while (select){cout << "**************************************" << endl;cout << "* [1] show            [2] push       *" << endl;cout << "* [3] pop             [4] length     *" << endl;cout << "* [5] clear           [6] destory    *" << endl;cout << "**************************************" << endl;cout << "請選擇:>";cin >> select;switch (select){case 1:mystack.show();break;case 2:cout << "請輸入要插入的值(-1結束):>";while (cin >> Item, Item != -1){mystack.push(Item);}break;case 3:mystack.pop();break;case 4:cout << "大小為:" << mystack.length()<<endl;break;case 5:mystack.clear();break;case 6:mystack.destory();break;default:break;}}return;}<img src="http://img.blog.csdn.net/20150531225418525?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZG91ZG91d2ExMjM0/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

【資料結構】用C++編寫棧及基本操作(包括入棧,出棧,獲得棧頂,摧毀,清空等等)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.