栈的基本操作

来源:互联网 发布:淘宝去年的交易订单 编辑:程序博客网 时间:2024/05/22 20:28
#include<stdio.h>#include<stdlib.h>#include<string.h>#define ok 1#define error 0#define overflow -1#define STACK_INIT_SIZE 100   //存储空间初始分配量#define STACKINCREMENT 10 //存储空间的分配增量typedef int Status;typedef int ElemType;/*栈的顺序存储表示*/typedef struct{    ElemType *base;    ElemType *top;  //栈顶指针    int stacksize;  //当前已分配的存储空间,以元素为单位}SqStack;/*基本操作函数的原型说明*/Status InitStack(SqStack &S);  //构造空栈SStatus GetTop(SqStack S,ElemType &e);   //返回栈顶元素Status Push(SqStack &S,ElemType e); //插入e为新的栈顶元素Status Pop(SqStack &S,ElemType &e); //删除栈顶元素用e返回/*基本操作的算法实现*/Status InitStack(SqStack &S){    S.base=(ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));    if(!S.base)        exit(overflow); //存储分配失败    S.top=S.base;    S.stacksize=STACK_INIT_SIZE;    return ok;}Status GetTop(SqStack S,ElemType &e){    if(S.top==S.base)        exit(overflow);    e=*(S.top-1);    return ok;}Status Push(SqStack &S,ElemType e){    if(S.top-S.base>=S.stacksize)//栈满,追加存储结构     {S.base=(ElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(ElemType));if(!S.base)exit(overflow);//存储分配失败 S.top=S.base+S.stacksize;S.stacksize+=STACKINCREMENT;     }    *S.top++ =e;    return ok;}//pushStatus Pop(SqStack &S,ElemType &e){if(S.top==S.base)return error;e= *--S.top;return ok;}//Pop/*简单的测试函数*/int main(){SqStack S;InitStack(S);int i,n;ElemType e;printf("Please input the SqStack's length: ");scanf("%d",&n);printf("\nThe sequence of pushstack is \n");for(i=0;i<n;i++){Push(S,i*2);printf("%d ",i*2);}printf("\n\n");printf("The top of stack is \n");GetTop(S,e);printf("%d\n\n",e);printf("The sequence of popstack is \n");for(i=0;i<n;i++){Pop(S,e);printf("%d ",e);}return 0;}

0 0
原创粉丝点击