自己手写一个栈【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;
}
相关推荐
翔云 OCR API14 分钟前
承兑汇票识别接口技术解析-开发者接口
开发语言·前端·数据库·人工智能·ocr
小白学大数据1 小时前
基于Splash的搜狗图片动态页面渲染爬取实战指南
开发语言·爬虫·python
xlq223221 小时前
22.多态(下)
开发语言·c++·算法
CoderYanger1 小时前
C.滑动窗口-越短越合法/求最长/最大——2958. 最多 K 个重复元素的最长子数组
java·数据结构·算法·leetcode·哈希算法·1024程序员节
未来之窗软件服务2 小时前
操作系统应用(三十三)php版本选择系统—东方仙盟筑基期
开发语言·php·仙盟创梦ide·东方仙盟·服务器推荐
是Dream呀2 小时前
昇腾实战|算子模板库Catlass与CANN生态适配
开发语言·人工智能·python·华为
零匠学堂20252 小时前
移动学习系统,如何提升企业培训效果?
java·开发语言·spring boot·学习·音视频
不会c嘎嘎2 小时前
【数据结构】AVL树详解:从原理到C++实现
数据结构·c++
小杨快跑~2 小时前
从装饰者到桥接再到工厂:模式组合的艺术
java·开发语言·设计模式
say_fall2 小时前
C语言编程实战:每日一题:随机链表的复制
c语言·开发语言·链表