///2014-09-04 ///author txh #include <iostream> using namespace std; template <class T> struct Node { Node<T> *next; T data; }; template <class T> class stack { public: stack() { head = new Node<T>; if(NULL == head) { cout<<"new head error"<<endl; } else { head->next = NULL; head->data = NULL; } } ~stack() { delete head; } void push(T elem) { Node<T> *p = new Node<T>; if(NULL == p) { cout<<"new Node error"<<endl; } else { p->data = elem; p->next = head->next; head->next = p; } } T pop() { T elem; Node<T> *p = head->next; if(p!=NULL) { elem = p->data; head->next = p->next; delete p; p = NULL; } else { cout<<"This stack is NULL"<<endl; return NULL; } return elem; } T top() { T elem; Node<T> *p = head->next; if(p != NULL) { elem = p->data; return elem; } else { cout<<"This stack is NULL"<<endl; return NULL; } } int stackSize() { int size = 0; Node<T> *p = head->next; while(p != NULL) { p = p->next; size++; } return size; } bool judgeEmpty() { Node<T> *p = head; if(p->next == NULL) { return true; } else { return false; } } private: Node<T> *head; }; int main(int argc,char *argv[]) { int i=0; stack<int> S; S.push(100); S.push(200); S.push(300); cout<<"the top:"<<S.top()<<endl; cout<<"the size:"<<S.stackSize()<<endl; if(S.judgeEmpty()) { cout<<"this empty"<<endl; } else { cout<<"this isn't empty"<<endl; } for(i=0; i<3; i++) { S.pop(); cout<<"the top:"<<S.top()<<endl; cout<<"the size:"<<S.stackSize()<<endl; } return 0; } |
|
来自: 海漩涡 > 《my program》