C语言 顺序栈

来源:互联网 发布:如何网络办理出国签证 编辑:程序博客网 时间:2024/05/23 00:33

初学者,有错误请指正,谢谢!

C语言顺序栈实现:

#include<stdlib.h>#include<stdio.h>#define NDEBUG#include<assert.h>#define STACK_INIT_SIZE 100#define STACKINCREMENT 10typedef int ElemType;typedef int Status;typedef struct{    ElemType *base;    ElemType *top;    int stacksize;}SqStack;//构造空栈SqStack *InitStack(){    SqStack *S=(SqStack*)malloc(sizeof(SqStack));    if(!S)exit(0);    S->base=(ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));    S->top=S->base;    S->stacksize=STACK_INIT_SIZE;    return S;}//判断是否为空栈Status IsEmpty(SqStack *S){    if(S->top==S->base)        return 1;    else return 0;}//返回栈大小int GetSize(SqStack *S){    if(IsEmpty(S))return 0;    else return S->top-S->base;}//元素出栈Status Pop(SqStack *S,ElemType *e){    assert(S);    if(IsEmpty(S))exit(0);    e=--(S->top);    printf("Element popped is %d\n",*e);    return 1;}//置空栈void SetEmpty(SqStack *S){    while(IsEmpty(S)!=1)        Pop(S,NULL);}//销毁栈void DestroyStack(SqStack *S){    assert(S);    if(IsEmpty(S)!=1)        SetEmpty(S);    free(S);}//遍历栈void StackTraverse(SqStack *S){    assert(S);    ElemType *Elem=S->base;    if(IsEmpty(S))        printf("Empty stack!\n");    for(;Elem!=S->top;Elem++){        printf("Element is %d\n",*Elem);    }}//返回栈顶ElemType GetTop(SqStack *S,ElemType e){    if(!IsEmpty(S))        return e=*(S->top-1);    return 0;}//元素入栈Status Push(SqStack *S,ElemType e){    assert(S);    //栈满,追加存储空间    if(S->top-S->base>=S->stacksize){        S->base=(ElemType*)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(ElemType));        if(!S->base)exit(0);        S->top=S->base+S->stacksize;        S->stacksize+=STACKINCREMENT;    }    *S->top++=e;    return 1;}int main(){    int i,item;    SqStack *S=InitStack();    for(i=0;i<5;i++){        int elem=rand()%100;        Push(S,elem);        printf("Element pushed is %d\n",elem);    }    StackTraverse(S);    for(i=0;i<5;i++){        Pop(S,&item);    }    SetEmpty(S);    printf("Set empty successfully.\n");    DestroyStack(S);    return 0;}


0 0
原创粉丝点击