#include<iostream.h> template<class T> struct STU { T data; STU<T> * next; }; template<class T> class LinkStack { public: LinkStack(){top=NULL;} ~LinkStack(); void Push(T x); T Pop(); T GetTop(){if(top!=NULL)return top->data;}; int Empty(){top==NULL?return 1:return 0;}; private: STU<T> * top; }; template<class T> class LinkStack<T>::Push(T x) { s=new STU; s->data=x; s->next=top; top=s; } template<class T> class LinkStack<T>::Pop() { STU<T> *p; T x; if(top=NULL)throw"Wrong"; x=top->data; p=top; top=top->next; delete p; return x; } int main() { LinkStack<int>s1; int m; do{ cout<<"-------------------------"<<endl; cout<<"输入1开始入栈"<<endl; cout<<"输入2开始弹栈"<<endl; cout<<"输入3开始读取栈顶"<<endl; cout<<"输入4开始判断是否空"<<endl; cin>>m; switch(m) { case 1: cout<<"请输入入栈的元素值"<<endl; cin>>a; s1.Push(a); break; case 2: cout<<"此操作为出栈"<<endl; s1.Pop(); break; case 3: int v; cout<<"此操作为读取栈顶"<<endl; s1.GetTop(); break; case 4: cout<<"此操作为判断栈为空"<<endl; s1.Empty(); break; } }while(1); return 0; }
原文地址:http://blog.csdn.net/qtintinq/article/details/40735639