Requirements:
File:stack.h
/*
Initializing a stack
Check that the stack is empty or full
To press an integer into the stack
POPs an integer from the stack.
Do not remove any yuan, tell the stack content output to standard output
The private members of the Stack class are as follows:
A private Oh member function for printing error messages
Three private data members constitute the private implementation of the Stack class, which provides support for the class interface.
*/
Implementation of the class
1#include <iostream>2 using namespacestd;3 4 5 classstack{6 Public : 7 enum{maxstack =5};8 //initialize stack, stack is empty9 voidInit () {top =-1;}Ten One voidPush (intN) { A if(Isfull ()) { -ErrMsg ("Full stack. Cant push"); - return ; the } -Arr[++top] =N; - } - + intpop () { - if(IsEmpty ()) { +ErrMsg ("Empty Stack. Popping dummy value."); A returnDummy_val; at } - - returnarr[top-- ]; - } - //Check if Statck is empty - BOOLIsEmpty () {returnTop <0 ;} in //Check if the stack is full - BOOLIsfull () {returnTop >= Maxstack-1;} to + //dump dumping the contents of the stack to the standard output in sequence from the end of the stack top - voiddump () { the for(inti = top; I >=0; i--) *cout <<'T'<< Arr[i] <<'\ n'; $ }Panax Notoginseng - the Private : + voidErrMsg (Const Char* msg)Const { ACerr <<"\n*** Stack operation failure:"<< msg <<'\ n'; the } + - inttop; $ intarr[maxstack]; $ intDummy_val; - -};
The test code is as follows:
#include <iostream>#include"stack.h" intMain () {Stack S1; S1.init (); S1.push (9); S1.push (4); S1.dump (); cout<<"Popping"<< S1.pop () <<'\ n'; S1.dump (); S1.push (8); S1.dump (); S1.pop (); S1.pop (); S1.dump (); S1.pop (); S1.dump (); S1.push (3); S1.push (5); S1.dump (); for(Unsigned i =0; I <Stack::MaxStack; i++) S1.push (1); S1.dump (); return 0;}
Debug results:
/* t4t9popping 4t9t8t9*** stack operation Failure:empty Stack. Popping dummy value.t5t3*** stack operation failure:full stack. cant push*** stack operation failure:full stack. cant Pusht1t1t1t5t3--------------------------------Process exited with return value 0Press any key to continue ... */
C + + implements stack "stack"