Stacks can be used in sequential tables or linked lists to store content, and this article uses sequential tables (arrays) to hold internal elements. The code is as follows: 1 #include <iostream>
2 using namespacestd;3 4 classMystack5 {6 Private:7 intl;8 intcount;9 int* Array;//note here that the member variable cannot be initialized with a member variable, not with Array[l]. Ten Public: OneMystack (intlen) A { -L=Len; -Count=0; thearray=New int[l]; - }; -Mystack ()//default constructor, maximum capacity is. - { +L= -; -Count=0; +array=New int[l]; A } at - voidPushintN) - { - if(count>l-1) - { -cout<<"Out of boundary"<<Endl; in return ; -}Else to { +array[count]=N; -count++; the } * } $ voidpop ()Panax Notoginseng { - if(count<0) the { +cout<<"empty!"<<Endl; A}Else the { +array[count--]=0; - } $ } $ - intTop () - { the returnArray[count]; - }Wuyi the BOOLIsEmpty () - { Wu return(count==0); - } About intstackSize () $ { - returncount+1; - } - }; A + intMain () the { -Mystack MS (Ten); $Ms.push (Ten); theMs.push (4); theMs.push (3); the if(Ms.isempty ()) thecout<<"is empty"<<Endl; -cout<<"is not empty"<<Endl; incout<<"length is:"<<ms.stacksize () <<Endl; the Ms.pop (); thecout<<"the top element after the stack is:"<<ms.top () <<Endl; About}
Operation Result:
C + + stacks (sequential table)