栈顺序存储

栈先进后出,类似一个杯子,栈是限定仅在表尾进行插入和删除操作的线性表,top是栈顶元素的下标,允许插入的一端为栈顶,允许删除的一端为栈底。
栈存在一个元素时top为0,所以空栈定义top为1

头文件和栈的结构定义

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

# define MAXSIZE 20

typedef int SElemType;
typedef struct
{
        SElemType data[MAXSIZE];
        int top;
}SqStack;

相关函数声明

bool visit(SElemType c); //输出一个元素
bool InitStack(SqStack *S); //初始化栈
bool ClearStack(SqStack *S); //清空栈
bool StackEmpty(SqStack S); //判断栈是否为空
int StackLength(SqStack S); //求栈的长度
bool GetTop(SqStack S,SElemType *e); //获取栈顶元素
bool Push(SqStack *S,SElemType e); //压栈
bool Pop(SqStack *S,SElemType *e); //弹出栈
bool StackTraverse(SqStack S); //从栈底元素依次输出栈

main函数

int main()
{
        int j;
        SqStack s;
        int e;
        if(InitStack(&s) == true)
                for(j = 1; j <= 10; j++)
                        Push(&s, j);
        printf("栈中元素依次为:");
        StackTraverse(s);
        Pop(&s, &e);
        printf("弹出的栈顶元素 e=%d\n", e);
        printf("栈空否:%d(1:空 0:否)\n", StackEmpty(s));
        GetTop(s, &e);
        printf("栈顶元素 e=%d 栈的长度为%d\n", e, StackLength(s));
        ClearStack(&s);
        printf("清空栈后,栈空否:%d(1:空 0:否)\n", StackEmpty(s));
        
        return 0;
}

输出一个元素

//输出一个元素
bool visit(SElemType c)
{
        printf("%d", c);

        return true;
}

初始化栈

//初始化栈
bool InitStack(SqStack *S)
{
        S->top = -1;

        return true;
}

清空栈

//清空栈
bool ClearStack(SqStack *S)
{
        /* S.data=(SElemType *)malloc(MAXSIZE*sizeof(SElemType)); */
        S->top = -1;

        return true;
}

判断栈是否为空

//判断栈是否为空
bool StackEmpty(SqStack S)
{
        if (S.top == -1)
                return true;
        else 
                return false;
}

获取栈顶元素

//获取栈顶元素
bool GetTop(SqStack S,SElemType *e)
{
        if ( StackEmpty(S) )
                return false;
        *e = S.data[S.top];
        return true;
}

压栈

//压栈
bool Push(SqStack *S,SElemType e)
{
        if (S->top == MAXSIZE - 1)
                return false;
        
        S->top++;
        S->data[S->top] = e;
        return true;
}

弹出栈

//弹出栈
bool Pop(SqStack *S,SElemType *e)
{
        if (S->top == -1)
                return false;

        *e = S->data[S->top];
        S->top--;
        return true;
}

从栈底依次输出每个元素

//从栈底依次输出每个元素
bool StackTraverse(SqStack S)
{
        int i = 0;
        
        while (i <= S.top)
        {
                visit(S.data[i++]);
        }
        printf("\n");
        return true;
}

猜你喜欢

转载自blog.csdn.net/qq_65337539/article/details/124790201