自己手写一个栈【C风格】

cpp 复制代码
#include <iostream>
//栈
#define MAX_SIZE 20
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

typedef int Status;//状态类型
typedef int ElemType;//元素类型

typedef struct SqStack
{
    ElemType data[MAX_SIZE];
    int top;
};


//初始化,方法1
//SqStack* InitStack()
//{
//    SqStack *s = (SqStack*)malloc(sizeof(SqStack));
//    s->top = 0;
//    return s;
//}
//初始化,方法2
Status InitStack(SqStack** s)
{
    //栈上的指针分配在堆上的内存,**s表示取到栈上指针的地址,才可以修改外部指针
    *s = (SqStack*)malloc(sizeof(SqStack));
    if ((*s) == NULL)return ERROR;
    (*s)->top = 0;
    return OK;
}

Status DestoryStack(SqStack* s)
{
    if (s != NULL)
    {
        free(s);
    }
    return OK;
}
Status ClearStack(SqStack* s)
{
    s->top = 0;
    return OK;
}
Status StackEmpty(SqStack* s)
{
    if (s->top > 0)
        return ERROR;
    return TRUE;
}
Status Push(SqStack* s, ElemType e)
{
    if (s == NULL)return ERROR;
    if ((s->top) >= MAX_SIZE)return ERROR;
    s->data[s->top] = e;
    s->top++;
    return OK;
}
Status Pop(SqStack* s)
{
    if (s == NULL)return ERROR;
    if (s->top == 0)return ERROR;
    s->top--;
}
int StackLength(SqStack* s)
{
    if (s == NULL)return ERROR;
    return s->top;
}

Status StackShow(SqStack* s)
{
    if(s == NULL)return ERROR;
    for (int i = 0; i < s->top; i++)
    {
        printf("%d-->", s->data[i]);
    }
    printf("***全部显示完成!\n");
    return OK;
}

int main()
{

    //方法一初始化
    // SqStack *s  = InitStack();
    //方法2初始化
    SqStack* s;
    InitStack(&s);

    if (s == NULL)
    {
        printf("内存不足!");
        return -1;
    }

    for (int i = 0; i < 10; i++)
    {
        Push(s, i);
    }
    StackShow(s);

    printf("删除5个元素:\n");
    Pop(s);
    Pop(s);
    Pop(s);
    Pop(s);
    Pop(s);
    StackShow(s);

    printf("是否为空:%d(1:是 0 :否)\n", StackEmpty(s));
    ClearStack(s);
    printf("清空后:\n");
    StackShow(s);
    printf("是否为空:%d(1:是 0 :否)\n", StackEmpty(s));

    DestoryStack(s);
    s = NULL;

    return 0;
}
相关推荐
程序喵大人4 分钟前
【C++并发系列】第一章:多线程读写同一个变量为什么会出错
开发语言·c++·多线程·并发
xiaoshuaishuai87 分钟前
C# vCenter跨云迁移的核心问题
开发语言·c#
zhengzhouliuhaha21 分钟前
智能医疗设备控费系统:以全院一体化管控,筑牢医疗资源“安全阀”
大数据·数据结构·人工智能·算法·安全·机器学习·软件需求
fox_lht44 分钟前
14.6.将错误重定向到标准错误
开发语言·后端·学习·rust
hahjee1 小时前
【鸿蒙PC】kcp 移植:AtomCode Skills 4 步速通单文件 C 库适配
c语言·华为·harmonyos
wzg19690226wzg1 小时前
rust 学习 泛型
开发语言·学习·rust
techdashen1 小时前
Rust 基础设施团队 2025 Q4 回顾与 2026 Q1 计划
开发语言·后端·rust
红宝村村长2 小时前
torch.autograd.Function.apply()
开发语言·python
AI科技星2 小时前
《数术工坊:非欧射影录》类型:硬核光影·几何本源
c语言·开发语言·网络·量子计算·agi