#include<iostream> using namespace std; const int MAXSIZE = 100; const int ADD = 10; struct stack{ int * base; int * top; int size; int ability; }; void IntStack(stack & sta)//初始化 { sta.base = (int *)malloc(MAXSIZE*sizeof(int)); sta.top = sta.base; sta.ability = MAXSIZE; sta.size = 0; }; void push(stack & sta,int a)//出栈 { if(sta.size >= sta.ability ) { sta.base = (int*)realloc(sta.base,(sta.ability+ADD)*sizeof(int)); if(!sta.base) exit(0); sta.top = sta.base + sta.size; } (*sta.top) = a; sta.top++; sta.size++; } int Pop(stack & sta)//入栈 { if(sta.size>0) { sta.size--; return *(--sta.top); } else throw exception(); } int GetSize(stack & sta)//返回栈长 { return sta.size; } int GetTop(stack & sta)//返回栈顶元素 { if(sta.size!=0) { return (*sta.base); } return -1; } void DestoryStack(stack & sta)//销毁 { free(sta.base); sta.base = sta.top; } void clear(stack & sta)//清空 { //压缩存储空间 if(sta.ability>MAXSIZE) { free(sta.base); sta.base = (int *)malloc(MAXSIZE*sizeof(int)); sta.ability = MAXSIZE; } sta.base = sta.top; sta.size = 0; } bool StackTraverse(stack & sta,bool(* visit)(int &))//遍历调用 { int * p = sta.base; for(;p!=sta.top;p++) { if(!(visit(*p))) { return false; } } return true; } bool fun(int & a) { a++; return true; } int main() { stack myStack;//创建 IntStack(myStack);//初始化 cout<<"大小:"<<GetSize(myStack)<<endl; push(myStack,1);//元素入栈 push(myStack,2); push(myStack,3); for(int *p = myStack.base;p!=myStack.top;p++)//遍历栈中的元素 cout<<(*p)<<" "; cout<<endl; cout<<"大小:"<<GetSize(myStack)<<endl; //所有元素出栈 for(;0!=myStack.size;) { cout<<Pop(myStack)<<" "; } cout<<endl; push(myStack,4);//元素入栈 push(myStack,5); push(myStack,6); cout<<GetTop(myStack)<<endl; StackTraverse(myStack,&fun);//处理栈中所有元素 for(int *p = myStack.base;p!=myStack.top;p++)//遍历栈中的元素 cout<<(*p)<<" "; cout<<endl; cout<<"大小:"<<GetSize(myStack)<<endl;//栈中元素的个数 }
原文:http://blog.csdn.net/yyc1023/article/details/23790351