/* stack class declarations; */ #ifndef _STACK_H_ #define _STACK_H_ #include <iostream> using namespace std; typedef int ElemType; typedef struct SNode{ ElemType data; struct SNode* pNext; }Node; class CStack{ public: CStack(); bool Push(ElemType elem); //push: insert an element to stack's top bool Pop(ElemType& elem); //pop : delete an element on stack's top int itsLength(); //get stack's length; void Traverse(); ~CStack(); private: Node* top; Node* base; }; #endif // _STACK_H_ /* class stack's definition; */ #include "stack.h" /* Parameter : none Return : none Description : */ CStack::CStack() { cout<<"[class default constructor.]"<<endl; base = NULL; top = NULL; } // class default constructor /* Parameter : ElemType Return : true or false Description : */ bool CStack::Push(ElemType elem) { Node* pNode = new Node; pNode->data = elem; pNode->pNext = top; top = pNode; return true; } // Push /* Parameter : ElemType& Return : true or false Description : */ bool CStack::Pop(ElemType& elem) { elem = top->data; top = top->pNext; return true; } // Pop /* Parameter : none Return : none Description : visit stack */ void CStack::Traverse() { Node* peak = top; while(peak) { cout<<"element : "<<peak->data<<endl; peak = peak->pNext; } } // Traverse /* Parameter : none Return : stack length Description : */ int CStack::itsLength() { int iLen = 0; Node* peak = top; while(peak) { ++iLen; peak = peak->pNext; } return iLen; } // itsLength /* Parameter : none Return : none Description : */ CStack::~CStack() { cout<<"[class default destructor. ]"<<endl; } // class default destructor //------------------------------------------------------------------------------ // Copyright (c) 2009 eryar All rights reserved. // // File : Main.cpp // Author : eryar@163.com // Date : 2009-12-31 // Version : 1.0v // // Description : // //============================================================================== #include "stack.h" int main(int argc, char* argv[]) { int iData; CStack stack; for (int i = 1; i < 10; ++i) { stack.Push(i); } cout<<"current length : "<<stack.itsLength()<<endl; stack.Traverse(); cout<<"================================="<<endl; cout<<"after pop 5 elements out : "<<endl; for (i = 1; i < 5; ++i) { stack.Pop(iData); } cout<<"current length : "<<stack.itsLength()<<endl; stack.Traverse(); return 0; }