C语言实现数组栈详解

1.结构体的组成

typedef struct Stack
{
	STDataType* a;
	int top;		
	int capacity;
}ST;

a:记录数组地址

top:记录栈顶位置

capacity:数组的容量

2.函数的实现

1.结构体初始化

void STInit(ST* pst)
{
	assert(pst);

	pst->a = NULL;
	pst->capacity = 0;

	// 表示top指向栈顶元素的下一个位置
	pst->top = 0;

	// 表示top指向栈顶元素
	//pst->top = -1;
}

因为 top相当于数组的下标

2.整个栈的销毁

void STDestroy(ST* pst)

{

assert(pst);

free(pst->a);

pst->a = NULL;

pst->top = pst->capacity = 0;

}

3.入栈,栈的扩容

void STPush(ST* pst, STDataType x)
{
	assert(pst);

	if (pst->top == pst->capacity)
	{
		int newcapacity = pst->capacity == 0 ? 4 : pst->capacity +2;
		STDataType* tmp = (STDataType*)realloc(pst->a, sizeof(STDataType) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc");
			return;
		}

		pst->a = tmp;
		pst->capacity = newcapacity;
	}

	pst->a[pst->top] = x;
	pst->top++;
}

1.当top=capacity

 realloc分配的空间是连续的,所以可以把它当数组用。把分配的内存地址赋值给a,然后扩容。

2.top<capacity

a存的是内存的地址,所以把x赋值a内地址的内存中,然后top增加

4.出栈

void STPop(ST* pst)
{
	assert(pst);
	assert(pst->top > 0);

	pst->top--;
}

 只需要把top的值减一,之后在入栈时,直接x覆盖掉之前的值

5.获取栈顶元素

STDataType STTop(ST* pst)
{
	assert(pst);
	
	assert(pst->top > 0);

	return pst->a[pst->top - 1];
}

因为top初始值为0,所以这里减一访问,[ ]解引用符号。

6.判断栈是否为空

bool STEmpty(ST* pst)
{
	assert(pst);

	
	return pst->top == 0;
}

 C语言没有bool类型,要引用头文件#include<stdbool.h>

7.获取栈所含元素个数

int STSize(ST* pst)
{
	assert(pst);

	return pst->top;
}

恭喜你学完啦,快去奖励自己一下吧!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值