动态顺序栈的C语言实现

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
#define FALSE -1
#define TRUE 1
#define OK 2
typedef struct
{
    int *base;
    int *top;
    int stackSize;


}SqStack;
///创建Stack
int CreateSqStack_S(SqStack *S)
{
    S->base=(int*)malloc(STACK_INIT_SIZE*sizeof(int));
    if(!S->base)
        return FALSE;
    S->top=S->base;
    S->stackSize=STACK_INIT_SIZE;
    return TRUE;
}
///压栈
int PushSqStack_S(SqStack *S,int e)
{
    if(S->top-S->base>=S->stackSize)
    {
        S->base=(int*)realloc(S->base,(S->stackSize+STACK_INCREMENT)*sizeof(int));
        if(!S->base)
            return FALSE;
        S->top=S->base+S->stackSize;
        S->stackSize=S->stackSize+STACK_INCREMENT;
    }
    *S->top=e;
    S->top=S->top+1;
    return TRUE;
}
///出栈
void PopSqStack_S(SqStack *S,int e)
{
    if(S->base==S->top)
        printf("The stack is NULL!\n");
    else
    {
        S->top=S->top-1;
        e=*S->top;
    }
}
///get栈顶元素
void GetTopSqStack_S(SqStack *S,int e)
{
    if(S->base==NULL)
        printf("The stack S is not exist!\n");
    else if(S->base==S->top)
        printf("The stack is NULL!\n");
    else
    {
        e=*(S->top-1);
        printf("The element of top:%d\n",e);
    }
}
///将栈清空
void ClearSqStack_S(SqStack *S)
{
    if(S->top!=S->base)
        S->top=S->base;
}
///销毁栈
void DeleteSqStack_S(SqStack *S)
{


    free(S->base);
    S->base=NULL;
    S->top=NULL;
    S->stackSize=0;
}
///遍历栈
int StackTravel(SqStack *S)
{
    int e;
    int *ptr;
    ptr=S->top;
    //对栈用visit遍历
    while(ptr>S->base)
    {
        ptr=ptr-1;
        e=*ptr;
        printf("%6d\n",e);
    }
    return OK;
}
int main()
{
    SqStack stack1;
    CreateSqStack_S(&stack1);
    int e;
    int x;
    PushSqStack_S(&stack1,5);
    PushSqStack_S(&stack1,3);
    GetTopSqStack_S(&stack1,e);
    //遍历栈
    StackTravel(&stack1);
    ClearSqStack_S(&stack1);
    for(x=1;x<5;x++)
    {
        PushSqStack_S(&stack1,x);
    }
    StackTravel(&stack1);
    GetTopSqStack_S(&stack1,e);
    DeleteSqStack_S(&stack1);
    GetTopSqStack_S(&stack1,e);
    return 0;

}


注意:

(1)遍历栈的时候不要直接用S.top执行,而需要重新定义一个指针;以免直接将栈清空;

(2)栈的基础操作有初始化栈,遍历栈,销毁栈,入栈操作,出栈操作;


猜你喜欢

转载自blog.csdn.net/qq_20406597/article/details/81011940