栈的基本应用

mac2026-04-07  6

栈的基本应用

栈是限定符在表未进行插入和删除操作的线性表。 具有先进后出的性质 栈

#include <iostream> using namespace std; template <class T> struct node { T data; node *next; }; template <class T> class linkstack{ public: linkstack(); //构造函数 ~linkstack(); //析构函数 void push(T x); //入栈 T pop(); //出栈 T getpop(); //取栈顶元素 int Empty(); // 判断栈空 private: node<T> *top; }; template <class T> linkstack<T>::linkstack() { top=NULL; } template <class T> void linkstack<T>::push(T x) { node<T> *s; s=new node<T>; s->data=x; s->next=top; top=s; } template <class T> T linkstack<T>::pop() { if(top==NULL){cout<<"栈空"<<endl;return 0;} node<T> *s=top; top=top->next; T x=s->data; delete s; return x; } template <class T> T linkstack<T>::getpop() { if(top==NULL){cout<<"栈空"<<endl;return 0;} return top->data; } template <class T> linkstack<T>::~linkstack() { node<T> *p=top; while(top!=NULL) { top=top->next; delete p; } } template <class T> int linkstack<T>::Empty() { if(top==NULL) return 1; else return 0; } int main() { linkstack<int> h; int x; cin>>x; while(x!=0) { h.push(x); cin>>x; } cout<<h.pop()<<endl; cout<<h.getpop()<<endl; cout<<h.Empty(); return 0; }
最新回复(0)