資料結構-棧的一些基礎操作c++代碼

來源:互聯網
上載者:User

標籤:

堆棧(簡稱棧) 是一種操作受限的線性表,只允許在表的同一端進行插入和刪除操作,且這些操作是按先進後出的原則進行的。
template <class T>struct SLNode{T data;                     //資料域SLNode<T> *next;            //指標域SLNode(SLNode *nextNode = NULL)                      //建構函式{next = nextNode;}SLNode(const T &item, SLNode *nextNode = NULL)      //建構函式{data = item;next = nextNode;}};//順序棧template <class T>class AStack{public:AStack(int MaxStackSize)                              //建構函式{size = MaxStackSize;stackArray = new T[MaxStackSize];top = -1;}~AStack()                              //解構函式{delete []stackArray;}bool Push(const T &item)              //向棧頂壓入一個元素{if (IsFull()){cout << "Pushing into a full stack!" << endl;return false;}stackArray[++top] = item;return true;}bool Pop(T &item)                     //從棧頂彈出一個元素{if (IsEmpty()){cout << "Poping from an empty stack!" << endl;return false;}item = stackArray[top--];return true;}bool Peek(T &item) const              //存取棧頂元素{if (IsEmpty()){cout << "Peeking from an empty stack!" << endl;return false;}item = stackArray[top];return true;}int IsEmpty() const                    //檢測棧是否為空白{return top == -1;}int IsFull() const                     //檢測是否滿棧{return top == size-1;}void clear()                           //清空棧{top = -1;}private:int size;                              //數組的規模T *stackArray;                         //存放堆棧元素的數組int top;                               //棧頂所在數組元素的下標};//鏈式棧類LStack的定義和實現template <class T>class LStack{public:LStack()                             //建構函式{top = NULL;}~LStack()                           //解構函式{clear();}void clear()                       //清空棧{SLNode<T> *temp;while(!IsEmpty()){temp = top->next;delete top;top = temp;}}bool Push(const T &item)          //向棧頂壓入一個元素{top = new SLNode<T>(item, top);return true;}bool Pop(T &item)                 //從棧頂彈出一個元素{if(IsEmpty()){cout << "Poping from an empty stack!" << endl;return false;}item = top->data;SLNode<T> *temp = top;top = top->next;}bool Peek(T &item) const         //讀取棧頂元素{if(IsEmpty()){cout << "Poping from an empty stack!" << endl;return false;}item = top->data;return true;}int IsEmpty() const{return top == NULL;}private:SLNode<T> *top;};


資料結構-棧的一些基礎操作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.