动态数组实现栈

和之前实现功能相同,分为一个函数声明文件,函数实现文件,以及测试文件

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>

typedef int Datatype;
typedef struct stack {
	Datatype* a;
	int capacity;//空间大小
	int top;//栈顶
}ST;
void STInit(ST* ps);//初始化
void STDestroy(ST* ps);//销毁
void STPush(ST* ps, Datatype x);//入栈
void STPop(ST* ps);//出栈
Datatype STTop(ST* ps);//拿出栈顶元素
int STSize(ST* ps);//数组长度
bool STEmpty(ST* ps);//判断是否为空

void STInit(ST* ps)
{
	assert(ps);
	ps->capacity = 0;
	ps->top = 0;
	ps->a = NULL;
}

//这里把栈顶初始化为0,入栈后让top++即可

void STDestroy(ST* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->top=ps->capacity = 0;
}
void STPush(ST* ps, Datatype x)
{
	assert(ps);
	if (ps->top == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		Datatype* tmp = (Datatype*)realloc(ps->a, sizeof(Datatype) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc failed");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newcapacity;
	}
	ps->a[ps->top] = x;
	ps->top++;
}//这里的realloc规定如果目标空间是空的话,这时相当于malloc创建内存

void STPop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);
	--ps->top;
}//这里需要判断栈中一个数据都没有的情况
Datatype STTop(ST* ps)
{
	assert(ps);
	assert(ps->top>0);
	return ps->a[ps->top-1];
}//因为top指向的是栈顶的下一个,所以这里需要让top-1
nt STSize(ST* ps)
{
	assert(ps);
	return ps->top;
}
bool STEmpty(ST* ps)
{
	assert(ps);
	return ps->top == 0;
}//这里需要引入<stdbool.h>头文件,判断为真返回frue


以上就是用顺序表实现栈功能的代码讲解,如有错误,欢迎指正,谢谢!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值