0
点赞
收藏
分享

微信扫一扫

C语言数据结构 顺序栈练习

zhongjh 2022-02-26 阅读 79
#include <stdio.h>
#include <stdlib.h>

//自定义bool
#define bool char
#define true 1
#define false 0

//栈的最大容量和类型定义
#define MaxSize 50
typedef int Elemtype;

//栈的结构
typedef struct SqStack
{
    //存储元素的数组
    Elemtype data[MaxSize];
    //记录栈顶的位置
    int top;
}SqStack;

//栈的初始化
bool InitStack(SqStack* S)
{
    //设置无元素时栈顶在-1,因为数组第一个元素下标为0
    S->top = -1;
    return true;
}

//栈判空
bool Empty(SqStack* S)
{
    if(S->top == -1) return true;
    else             return false;
}

//压栈
bool Push(SqStack* S, Elemtype e)
{
    //判断栈是否为满
    if(S->data[S->top] == MaxSize-1) return false;
    //压栈
    S->data[++S->top] = e;
    return true;
}

//出栈并把栈顶元素赋值给e
bool Pop(SqStack* S, Elemtype* e)
{
    //判断栈是否为空
    if(S->top == -1) return false;
    //出栈
    *e = S->data[S->top--];
    return true;
}

//读栈并把栈顶元素赋值给e
bool PrintStack(SqStack* S, Elemtype* e)
{
    if(S->top == -1) return false;
    //出栈
    *e = S->data[S->top];
    return true;
}


int main()
{
    SqStack S;//定义结构
    InitStack(&S);//初始化

    return 0;
}
举报

相关推荐

0 条评论