//自訂鏈表形式的堆棧#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;}