栈(1)

来源:互联网 发布:iebook制作软件 编辑:程序博客网 时间:2024/06/11 05:10
#include<iostream>using namespace std;const int stackinitsize=100;const int stackincrement=10;typedef struct{ char *base; char *top; int stacksize;} SqStack;//输出操作void visit(char e){cout<<(int)e<<endl;}//初始化bool InitStack(SqStack &S){S.base=(char *)malloc(stackinitsize*sizeof(char));    if(!S.base)return false;S.top=S.base;S.stacksize=stackinitsize;return true;}//销毁bool DestoryStack(SqStack &S){while(S.base!=S.top){free(S.top--);}free(S.top);S.base=S.top=NULL;S.stacksize=0;return true;}//清除bool ClearStack(SqStack &S){S.top=S.base;return true;}//判断是否为空bool StackEmpty(SqStack S){if(S.top==S.base)return true;elsereturn false;}//长度int StackLength(SqStack S){return S.stacksize;}//获取栈顶元素bool GetTop(SqStack S,char &e){if(S.top==S.base)return false;e=*(S.top-1);return true;}//压栈bool Push(SqStack &S,char e){if(S.top-S.base>=S.stacksize){S.base=(char *)realloc(S.base,(S.stacksize+stackincrement)*sizeof(char));if(!S.base){return false;}S.top=S.base+S.stacksize;    S.stacksize=S.stacksize+stackincrement;}*S.top++=e;return true;}//退栈bool Pop(SqStack &S,char &e){if(S.top==S.base)return false;e=*(--S.top);return true;}//从栈底向栈顶访问bool StackTraverse(SqStack S,void (*visit)(char e)){int i=0;while((S.base+i)!=S.top){visit(*(S.base+i));i++;}return true;}int main(){SqStack S;InitStack(S);for(int i=0;i<10;i++)Push(S,(char)i);StackTraverse(S,visit);for(int j=0;j<10;j++){char e;Pop(S,e);printf("%d\n",e);}return 0;}

原创粉丝点击