链栈

来源:互联网 发布:数控转塔冲床编程招聘 编辑:程序博客网 时间:2024/06/16 21:52
#include <iostream>#include<stack> using namespace std;template <class T>struct Node{T data;Node<T>*next;};template <class T>class LinkStack{public:LinkStack(){top=NULL;}void push (T x);int pop();int gettop();int empty();void print();private:Node<T> *top;};template <class T>void LinkStack<T>::push(T x){Node<T>*s=NULL;s=new Node<T>;s->data=x;s->next=top;top=s;}template <class T>int LinkStack<T>::pop(){   if(top==NULL)throw"上溢";T x;Node<T>*p=NULL;x=top->data;p=top;top=top->next;delete p;return x;}template <class T>void LinkStack<T>::print(){Node<T>*p;p=top->next;while(p!=NULL){cout<<p->data<<' ';p=p->next;}}template <class T>int LinkStack<T>::empty(){if(top==NULL)return 1;else return 0;}template <class T>int LinkStack<T>::gettop(){if(top!=NULL)return top->data;}int main(){LinkStack<int> s;if(s.empty())cout<<"栈为空"<<endl;else cout<<"栈非空"<<endl;cout<<"依次将1,2,3入栈"<<endl;    s.push(1);s.push(2);s.push(3);cout<<"栈顶元素:"<<endl;cout<<s.gettop()<<endl;cout<<"\n"<<endl;cout<<"3元素出栈"<<endl;s.pop();cout<<"栈顶元素:"<<endl;cout<<s.gettop()<<endl;return 0;}

原创粉丝点击