静态数组的顺序栈C语言实现

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAX_STACK_SIZE 100 //栈的大小
#define ERROR -1
#define OK 1
typedef struct sqstack
{
    int stack_array[MAX_STACK_SIZE];
    int top;
    int bottom;
}SqStack;
///栈的初始化
int Init_Stack(SqStack *S)
{
    S->bottom=S->top=0;
}
///进栈
int PushStack(SqStack *S, int e)
{
    //使数据元素e进栈成为新的栈顶元素
    if(S->top==MAX_STACK_SIZE-1)
    {
        printf("栈满,返回错误标志");
        return ERROR;
    }
    S->top=S->top+1;
    S->stack_array[S->top]=e;
    return OK;
}
///出栈
int PopStack(SqStack *S, int e)
{
    if(S->top==0)
    {
        printf("栈空,无法出栈元素");
        return ERROR;
    }
    e=S->stack_array[S->top];
    S->top--;
    return OK;
}
///遍历栈
int StackTravel(SqStack *S)
{
    int e;
    int ptr;
    ptr=S->top;
    while(ptr>S->bottom)
    {
        e=S->stack_array[ptr];
        ptr=ptr-1;
        printf("%d\n",e);
    }
    return OK;
}
///取出栈顶元素
int GetTopStack(SqStack *S, int e)
{
    if(S->top==0)
    {
        printf("栈不存在或者栈为空\n");
        return ERROR;
    }
    else
    {
        e=S->stack_array[S->top];
        printf("栈顶元素为:%d\n",e);
    }
}
///清空栈
int destroyStack(SqStack *S)
{
    if(S->top!=S->bottom)
    {
        S->top=0;
    }
}
int main()
{
    SqStack stack2;
    int m,x,n;
    Init_Stack(&stack2);
    printf("输出初始化后的栈的栈顶元素:\n");
    GetTopStack(&stack2,n);
    for(x=1;x<5;x++)
    {
       PushStack(&stack2,x);
    }
    printf("压入了4个元素后,输出栈中元素:\n");
    StackTravel(&stack2);
    printf("输出栈的栈顶元素:\n");
    GetTopStack(&stack2,n);
    destroyStack(&stack2);

}


猜你喜欢

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