数据结构之栈(二)

Stack.c

1.头文件的声明

#include "Stack.h"

2.初始化和销毁函数的定义

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

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

3.入栈和出栈函数的定义

//插入
void STPush(ST* ps, STDataType x)
{
? ? assert(ps);
? ? if (ps->top == ps->capacity)
? ? {
? ? ? ? int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
? ? ? ? STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType) * newCapacity);
? ? ? ? if (tmp == NULL)
? ? ? ? {
? ? ? ? ? ? perror("realloc fail");
? ? ? ? ? ? exit(-1);
? ? ? ? }

? ? ? ? ps->a = tmp;
? ? ? ? ps->capacity = newCapacity;
? ? }

? ? ps->a[ps->top] = x;
? ? ps->top++;
}

//删除栈顶元素
void STPop(ST* ps)
{
? ? assert(ps);
? ? assert(ps->top > 0);
? ? --ps->top;
}

4.查找栈顶元素和长度计算函数以及判空函数的定义

//查找栈顶元素
STDataType STTop(ST* ps)
{
? ? assert(ps);
? ? assert(ps->top > 0);
? ? return ps->a[ps->top - 1];
}

//长度计算
int STSize(ST* ps)
{
? ? assert(ps);

? ? return ps->top;
}

//判断是否为空
bool STEmpty(ST* ps)
{
? ? assert(ps);

? ? return ps->top == 0;
}

(3)Test.c

1.头文件的声明

#include "Stack.h"

?

文章链接: /26231.html

文章标题:数据结构之栈(二)

文章版权:云服务器租用科技所发布的内容,部分为原创文章,转载请注明来源,网络转载文章如有侵权请联系我们!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
建站教程

数据结构之栈

2023-12-21 17:47:20

建站教程

数据结构之栈(三)

2023-12-22 10:05:17

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧

云服务器租用科技 - 最新云主机促销服务器租用优惠

http://www.vxiaotou.com