1. Sequential storage
//sequential storage implementations of stacks//Stack.h#ifndef Stack_h_#defineStack_h_#defineElementType int#defineMaxSize 100typedefstruct_node{ElementType data[maxsize]; inttop;} Node;classstack{Private: Node data; Public: Stack (); ~Stack (); intIsfull (); voidPush (ElementType item); intIsEmpty (); ElementType Pop ();};#endif//Stack.cpp#include"Stack.h"#include<iostream>Stack::stack () {data.top= -1;} Stack::~Stack () {}intStack::isfull () {if(Data.top = = (MaxSize-1)) return 1; Else return 0;}voidStack::P ush (ElementType item) {if(Isfull () = =1) {Std::cout<<"Stack Overflow"<<Std::endl; return; } data.data[+ + (data.top)] =item;}intStack::isempty () {if(Data.top = =-1) return 1; Else return 0;} ElementType Stack::P op () {if(IsEmpty ()) Std::cout<<"stack is empty"<<Std::endl; returndata.data[(data.top)--];}
2, chain-type storage
//chained storage implementations of stacks//PStack.h#ifndef Pstack_h_#definePstack_h_#defineElementType int#defineMaxSize 100typedefstruct_pnode{ElementType data; _pnode*Next;} Pnode;classpstack{Private: Pnode*top; Public: Pstack (); ~Pstack (); intIsfull (); voidPush (ElementType item); intIsEmpty (); ElementType Pop ();};#endif//PStack.cpp#include"PStack.h"#include<iostream>pstack::P stack () {Top=NewPnode (); Top->next =NULL;} Pstack::~Pstack () {Deletetop;}voidpstack::P ush (ElementType item) {Pnode* s =NewPnode (); S->data =item; S->next =top; Top=s;}intPstack::isempty () {if(top = =NULL)return 1; Else return 0;} ElementType pstack::P op () {if(IsEmpty ()) Std::cout<<"stack is empty"<<Std::endl; Pnode*s; S=top; ElementType e= s->data; Top= top->Next; DeleteBS; returne;}
3. Test sample
#include <iostream>#include"PStack.h"using namespacestd;intMain () {Pstack st; St. Push (5); St. Push (6); St. Push (2); intA =St. Pop (); intb =St. Pop (); cout<<"A, B"<< a <<" "<< b <<Endl; St. Push (b/a); A=St. Pop (); b=St. Pop (); cout<<"A, B"<< a <<" "<< b <<Endl; St. Push (b+a); St. Push (3); St. Push (4); A=St. Pop (); b=St. Pop (); cout<<"A, B"<< a <<" "<< b <<Endl; St. Push (b*a); A=St. Pop (); b=St. Pop (); St. Push (b-a); cout<<"A, B"<< a <<" "<< b <<Endl; cout<<"according to the suffix expression is the value of the computed 5+6/2-3*4:"<< St. Pop () <<Endl; System ("Pause"); return 0;}
Data structure (2)--Stack