- #include<iostream>
- using namespace std;
- template<typename T>struct node{
- T data;
- node<T> *next;
- };
- template<typename T>class stack{
- private :
- node<T> *top;
- int length;
- public:
- stack()
- {
- top=new node<T>;
- top=NULL;
- length=0;
- }
- ~stack()
- {
- clearStack();
- }
- void clearStack()
- {
- node<T> *p=top;
- node<T> *q;
- while(p!=NULL)
- {
- q=p->next;
- delete p;
- p=q;
- length--;
- }
- top=NULL;
- }
- int getLength()
- {
- node<T> *p=top;
- int n=0;
- while(p!=NULL)
- {
- p=p->next;
- n++;
- }
- return n;
- }
- void push(T e)
- {
- node<T> *p=new node<T>;
- p->data=e;
- p->next=top;
- length++;
- top=p;
- }
- bool pop(T &e)
- {
- if(NULL==top)
- return false;
- node<T> *p=top;
- e=p->data;
- top=p->next;
- length--;
- }
- void print()
- {
- node<T> *p=top;
- while(NULL!=p)
- {
- cout<<p->data<<" ";
- p=p->next;
- }
- cout<<endl;
- }
- };
- int main()
- {
- stack <int> La;
- cout<<La.getLength();
- for(int i=1;i<5;i++)
- La.push(i);
- cout<<La.getLength()<<",";
- La.print();
- int e;
- for(int i=1;i<5;i++)
- {
- La.pop(e);
- La.print();
- }
- for(int i=1;i<5;i++)
- La.push(i);
- La.print();
- La.clearStack();
- cout<<La.getLength();
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/300720134888.html
来源: http://www.codesnippet.cn/detail/300720134888.html