栈的实现(C语言)

我们是用顺序表的结构来实现栈 ,栈是一种数据先进后出,后进先出的数据结构

1.建立头文件

#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#pragma warning(disable:4996)

typedef int STdatatype;
typedef struct stack
{
	STdatatype* a;
	int top;
	int capacity;
}ST;


void StackInit(ST* ps);  //初始化
void StackDestroy(ST* ps);//销毁
void StackPush(ST* ps, STdatatype x);//依次插入数据
void StackPop(ST* ps);//删除栈顶元素


STdatatype StackTop(ST* ps);//返回栈顶元素
bool StackEmpty(ST* ps);//判断是否为空
int StackSize(ST* ps);//返回元素个数

2.栈的初始化

void StackInit(ST* ps)   //初始化
{
    assert(ps);
    ps->a = NULL;
    ps->capacity = ps->top = 0;
}

把a指针指向空,数据个数和容量初始化为0

3.栈的销毁

void StackDestroy(ST* ps)  //销毁
{
    assert(ps);
    free(ps->a);
    ps->a = NULL;
    ps->capacity = ps->top = 0;
}

因为已经为a开辟了空间,所以需要释放

4.栈的数据插入

void StackPush(ST* ps, STdatatype x)  //依次插入数据
{
    assert(ps);
    if (ps->top == ps->capacity)
    {
        int newca = ps->capacity == 0 ? 4 : ps->capacity * 2;
        STdatatype* tmp = (STdatatype*)realloc(ps->a, newca * sizeof(STdatatype));
        if (tmp == NULL)
        {
            perror("realloc fail");
            exit(-1);
        }
        ps->a = tmp;
        ps->capacity = newca;
    }
    ps->a[ps->top] = x;
    ps->top++;
}

首先判断容量是否充足,如果已经满容量,先进行扩容。然后让a指向新开辟的空间,让容量大小变成newca,最后在ps->top位置插入x,然后top++。

5.删除栈顶的数据

void StackPop(ST* ps)    //删除栈顶端的数据
{
    assert(ps);
    assert(!StackEmpty(ps));
    ps->top--;
}

首先判断ps,以及ps是否为空,然后直接top--。

6.返回栈顶的数据

STdatatype StackTop(ST* ps)    //返回栈顶的数据
{
    assert(ps);
    assert(!StackEmpty(ps));
    return ps->a[ps->top - 1];
}

7.判断栈是否为空

bool StackEmpty(ST* ps)      //判断是否为空
{
    assert(ps);
    return ps->top == 0;
}

8.返回元素个数

int StackSize(ST* ps)      //计算数据数量
{
    assert(ps);
    return ps->top;
}

9.测试栈

void test()
{
    ST st;
    StackInit(&st);
    StackPush(&st,1);      //插入1
    StackPush(&st, 2);     //插入2
    StackPush(&st, 3);      //插入3 
    printf("%d \n", StackTop(&st));  //打印3
    StackPop(&st);                    //删除3
    printf("%d \n", StackTop(&st));   //打印2
    StackPop(&st);                    //删除2
    StackPush(&st, 4);         //插入4
    StackPush(&st, 5);          //插入5 

    while (!StackEmpty(&st))       //只要栈不为空就一直打印栈顶元素 并删除栈顶元素
    {
        printf("%d ", StackTop(&st));
        StackPop(&st);
    }
    printf("\n");
}
int main()
{
    test();
    return 0;
}

最后为测试结果

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青山是哪个青山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值