C语言栈的函数实现

ST.h

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int STDataType;
typedef struct ST {
    STDataType* arr;
    int top;
    int capacity;
}stack;
void StackInit(stack* ps);//初始化与销毁
void StackDestroy(stack* ps);
void StackPush(stack* ps, STDataType x);//压栈
STDataType StackTop(stack* ps);//获取栈顶元素
void StackPop(stack* ps);//出栈
bool EmptyST(stack* ps);//判断是否为空
int StackSize(stack* ps);//返回栈内元素个数

ST.c

#include"ST.h"
void StackInit(stack* ps)//初始化与销毁
{
    ps->arr = NULL;
    ps->top = 0;//栈的下一个元素下标,也可以用-1,表示正在栈顶的元素下标
    ps->capacity = 0;//空间赋0
}
void StackDestroy(stack* ps)
{
    free(ps->arr);
    ps->arr = NULL;
    ps->capacity = 0;
    ps->top = 0;//只销毁了栈的空间,记录栈信息的结构体未销毁
}
void StackPush(stack* ps, STDataType x)//压栈
{
    assert(ps);//检查记录栈的变量不为空
//不用单独写判断空间申请空间的函数
    if (ps->top == ps->capacity)
    {
        int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;//新空间容量,为0或几倍
        STDataType* newarr = (STDataType*)realloc(ps->arr, sizeof(STDataType) * newcapacity);  //新定义变量接受,防止realloc返回空指针导致原指针接受,空间丢失
        assert(newarr);
        ps->arr = newarr;//接受新空间,老空间已经被realloc释放了
        ps->capacity = newcapacity;//记录空间变化
    }
    ps->arr[ps->top] = x;
    ps->top++;
}
//获取栈顶数据,去除顶在一起是出栈
STDataType StackTop(stack* ps)//获取栈顶元素
{
    assert(ps);
    assert(ps->top);
    return ps->arr[ps->top - 1];
}
void StackPop(stack* ps)//去顶
{
    assert(ps);
    assert(ps->top);//栈不为空
    ps->top--;
}
bool EmptyST(stack* ps)//判断是否为空
{
    assert(ps);
    return !ps->top;
}
int StackSize(stack* ps)//返回栈内元素个数
{
    assert(ps);
    return ps->top - 1;
}

main.c

#include"ST.h"
int main()
{
    stack x;
    StackInit(&x);
    StackPush(&x, 1);
    StackPush(&x, 2);
    StackPush(&x, 3);
    StackPush(&x, 4);
    StackPush(&x, 5);
    while (!EmptyST(&x))
    {
        printf("%d ", StackTop(&x));
        StackPop(&x);
    }
    printf("\n");
    StackDestroy(&x);
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值