自己手写一个栈【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;
}
相关推荐
吃饱很舒服1 分钟前
kotlin distinctBy 使用
android·java·开发语言·前端·kotlin
Cindy辛蒂2 分钟前
python办公自动化之分析日志文件
开发语言·python
续亮~8 分钟前
6、Redis系统-数据结构-07-QuickList
数据结构·数据库·redis
优秀的颜20 分钟前
RabbitMQ(集群相关部署)
开发语言·后端
ToBeWhatYouWannaBe.42 分钟前
代码随想录-Day49
java·数据结构·算法·leetcode
Little Tian1 小时前
插入排序——C语言
c语言·数据结构·算法·排序算法
天若有情6731 小时前
【澳门风云】用C开发一个模拟一个简单的扑克牌比大小的游戏
c语言·开发语言·游戏
韩楚风1 小时前
【手写数据库内核组件】0201 哈希表hashtable的实战演练,多种非加密算法,hash桶的冲突处理,查找插入删除操作的代码实现
c语言·数据结构·数据库·哈希算法·散列表
镜花照无眠1 小时前
python破解字母已知但大小写未知密码
开发语言·python
chenhua10086111 小时前
artts升级版本后常见的编译错误(定期更新......)
开发语言·javascript