[C++]資料結構:鏈表形式的堆棧LinkedStack類

來源:互聯網
上載者:User
//自訂鏈表形式的堆棧#include<iostream>using namespace std;template<class T>class Node{public:T data;Node<T> *link;};template<class T>class LinkedStack{public:LinkedStack(){top=0;}~LinkedStack();bool IsEmpty()const{return top==0;}bool IsFull()const;T Top()const;LinkedStack<T>& PushStack(const T&x);LinkedStack<T>& PopStack(T&x);Node<T> *top;void Show()const;};  class OutOfBounds{        public:            OutOfBounds(){            cout<<"Out Of Bounds!"<<endl;            }    };        //記憶體不足的異常類    class NoMem{        public:            NoMem(){                cout<<"No Memory!"<<endl;            }    };    //使new引發NoMem異常而不是xalloc異常    //如果要恢複原始行為可以做以下調用    //_set_new_handler(Old_Handler);    int my_new_handler(size_t size){        throw NoMem();    }       template<class T>void LinkedStack<T>::Show()const{  Node<T> *current = top;while(current) {        cout<<current->data<<endl;  current=current->link;    }  }    //堆棧的析構方法template<class T>LinkedStack<T>::~LinkedStack(){Node<T>*next;while(top){next=top->link;delete top;top=next;}}//判斷當前的堆棧有木有滿載template<class T>bool LinkedStack<T>::IsFull()const{try{Node<T>*p = new Node<T>;delete p ;return false;}catch(NoMem){return true;}}//返回當前堆棧的頭元素資料template<class T>T LinkedStack<T>::Top()const{if(IsEmpty())throw OutOfBounds();return top->data;}//將資料壓進堆棧template<class T>LinkedStack<T>& LinkedStack<T>::PushStack(const T&x){Node<T>*p = new Node<T>;p->data = x;p->link = top;top = p;return *this;}//刪除棧頂元素並將其送入xtemplate<class T>LinkedStack<T>&LinkedStack<T>::PopStack(T&x){if(IsEmpty())throw OutOfBounds();x=top->data;Node<T>*p = top ;top = top->link;delete p;return *this;}int main(){LinkedStack<int> myStack;myStack.PushStack(1);myStack.PushStack(2);myStack.PushStack(3);myStack.PushStack(4);myStack.PushStack(5);myStack.PushStack(6);myStack.Show();int popNode;myStack.PopStack(popNode);cout<<"Pop One From Stack : "<<popNode<<endl;myStack.Show();return 0;}

聯繫我們

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