数据结构学习之链栈c++实现

来源:互联网 发布:it was until 编辑:程序博客网 时间:2024/06/13 16:45
//链栈,c++实现 2012-10-3 18:12:21#include <iostream>using namespace std;template <class Telem> class  LinkStack;template <class Telem> class Node{ friend class  LinkStack <Telem>;Telem data;Node <Telem> *next;public: Node(Telem d=0,Node <Telem> *n=NULL):data(d),next(n){};};template <class Telem> class  LinkStack // :public Stack<Telem>{ private:Node <Telem> *top;public:LinkStack():top(NULL){};~LinkStack(){delete top;};void init(){top=NULL;};int  leng();Telem pop();Telem gettop();bool push (Telem& el);bool empt(){return top==NULL;};bool full(){return false;};void inver();void inver0();void show(){LinkStack<Telem> p;Telem data;while(!this->empt()){data=this->pop();p.push(data);}while(!p.empt()){data=p.pop();cout<<data<<" ";this->push(data);}cout<<endl;   };};template <class Telem> bool LinkStack<Telem>::push(Telem& el){ Node <Telem> *p;p= new Node <Telem>;p->data=el;p->next=top;top=p;return true;};template <class Telem> Telem LinkStack <Telem>::pop(){ Telem el;if (top == NULL) return NULL;else {el = top->data;top = top->next;return(el);}};template <class Telem> int LinkStack <Telem>::leng(){ Node <Telem> *p; int i;p=top; i=0;while (p!=NULL){ p = p->next; i++;};return i;};template <class Telem> void LinkStack<Telem>::inver0(){Node <Telem> *p,*s;p= top;  top=NULL;while (p!=NULL ){s=p; p=p->next;s->next=top;top=s;};};template <class Telem> void LinkStack<Telem>::inver(){int i,n=0; Telem arr[64];while( ! empt()) arr[n++]= pop();for(i=0;i<n;i++) push(arr[i]);};int main(){char a[]={'a','b','c','d','e','f','g','h','i','j'};LinkStack <char> stack;for(int i=0;i<sizeof(a);i++){stack.push(a[i]);}stack.show();cout<<stack.empt()<<endl;cout<<stack.full()<<endl;cout<<stack.pop()<<endl;stack.show();cout<<"inver:"<<endl;stack.inver();stack.show();stack.inver0();stack.show();return 0;}