Disclaimer: Transfer from http://www.cnblogs.com/pengshao/archive/2011/12/26/2301461.html
Header file StackDemo.h
1 #pragmaOnce//commonly used C + + pragma, the header file is the first to join, to ensure that the header files are only compiled once2typedefintDataType;3 Const intMaxstatcksize = -;//define the size of the stack4 classStackdemo5 {6 Public:7 //To analyze a constructor function8Stackdemo (void);9~stackdemo (void);Ten One //push stack out stack operation A voidPush (DataType item); -DataType Pop (void); - voidClearstack (void); the - //access the top of the stack, return to the top of the stack current subscript -DataType Peek (void)Const; - + //detection of vertebral stack - BOOLIsEmpty (void)Const; + BOOLIsfull (void)Const; A at Private: - DataType stacklist[maxstatcksize]; - intTos//Top of Stack -};View Code
Implement StackDemo.cpp
1#include"StackDemo.h"2#include <iostream>3 using namespacestd;4Stackdemo::stackdemo (void)5 {6 This->tos =-1;7 }8Stackdemo::~stackdemo (void)9 {Ten This->tos =-1; One } A voidStackdemo::P ush (DataType Item) - { - //whether the stack is full the if(!isfull ()) - { -tos++; - This->stacklist[tos] =item; + - } + Else Acout <<"Out of the stack!"<<Endl; at } - -DataType Stackdemo::P op (void) - { - if(!isEmpty ()) - { in intEBP =tos; -TOS--; to returnSTACKLIST[EBP]; + } - Else the return-1; * } $ Panax NotoginsengDataType Stackdemo::P eek (void)Const - { the returntos; + } A the voidStackdemo::clearstack () + { - for(inti = TOS; I >=0; i--) $Stacklist[i] =0; $TOS =-1; -cout <<"Clear Stack done!"<<Endl; - } the - BOOLStackdemo::isfull (void)ConstWuyi { the returnTos > Maxstatcksize?true:false; - } Wu - BOOLStackdemo::isempty (void)Const About { $ returnTOS <0?true:false; -}View Code
Main.cpp
1#include <iostream>2#include"StackDemo.h"3 using namespacestd;4 5 intMain ()6 {7Stackdemo *SD =NewStackdemo ();8Sd->push (Ten);//Press Stack9Sd->push ( -);//Press StackTenSd->push ( -);//Press Stack Onecout <<"Stack TOP:"<< Sd->peek () <<Endl; A for(intI=0;i<3; i++) -cout <<"POP:"<< Sd->pop () <<Endl; - thecout <<"Stack TOP:"<< Sd->peek () <<Endl; - - return 0; - +}View Code
Reproduced Getting started with the C + + stack