顺序栈基本操作

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

#define STACK_INIT_SIZE 100

typedef struct{
    int *base;
    int *top;
    int stacksize;
}SqStack;

int InitStack(SqStack &S){
    S.base=(int *)malloc(STACK_INIT_SIZE *sizeof(int));
    if(!S.base) exit(OVERFLOW);
    S.top=S.base;
    S.stacksize=STACK_INIT_SIZE;
    return 1;
}

int Push(SqStack &S,int e){
    if(S.top-S.base>=S.stacksize){
        printf("STACK S is FULL\n");
        return 0;
    }
    *S.top++=e;
    return 1;
}

int Pop(SqStack &S,int &e){
    if(S.top==S.base)
        return 0;
    e=*--S.top;
    return e;
}

int GetTop(SqStack S){
    if(S.top!=S.base)
        return *(S.top-1);
    return 0;
}

void StackTraverse(SqStack S){
    int length=0,e;
    while(S.top!=S.base){
        e=GetTop(S);
        printf("%d ",e);
        S.top--;
        length++;
    }
    printf("\n");
    printf("The length of S is %d\n",length);
}

int DestoryStack(SqStack &S){
    free(S.base);
    S.base=NULL;
    S.top=NULL;
    S.stacksize=0;
    return 1;
}

int main(){              //记几个测试代码,可随意更改
    SqStack S;
    int n,i,e;
    InitStack(S);
    scanf("%d",&n);
    for(i=1;i<=n;i++){
        Push(S,i);
    }
    StackTraverse(S);
    e=Pop(S, e);
    printf("%d\n",e);
    StackTraverse(S);
    DestoryStack(S);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_46200758/article/details/108230977