栈基本功能的实现

本文详细介绍了使用C语言实现的栈数据结构,包括栈的初始化、销毁、插入、删除、判断空栈、获取栈大小和返回栈顶元素的方法。通过顺序存储方式,展示了栈的典型操作过程。
摘要由CSDN通过智能技术生成

栈是只允许在一端进行插入或删除的线性表,遵循先入后出的原则

以下是栈的基本功能:

typedef int STDataType;
typedef struct Stack
{
	STDataType* a;
	int capacity;
	int top;
} ST;
//初始化
void STInit(ST* ps);
//销毁
void STDestroy(ST* ps);
//插入
void STPush(ST* ps, STDataType x);
//删除
void STPop(ST* ps);
//判空
bool STEmpty(ST* ps);
//数据个数
int STSize(ST* ps);
//返回栈顶元素
STDataType STTop(ST* ps);

要说明一点,本篇栈的实现是采取顺序存储,并且栈顶元素位置初始化为0

初始化:

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->capacity = 0;
	ps->top = 0;
}

插入元素:

void STPush(ST* ps, STDataType x)
{
	assert(ps);
	if (ps->capacity == ps->top) {
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		STDataType* tem = (STDataType*)realloc(ps->a, sizeof(STDataType) * newcapacity);
		if (tem == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->a = tem;
		ps->capacity = newcapacity;
	}
	ps->a[ps->top] = x;
	ps->top++;
}

删除元素:

void STPop(ST* ps)
{
	assert(ps);
	assert(!STEmpty(ps));
	ps->top--;
}

判定栈是否为空:

bool STEmpty(ST* ps)
{
	assert(ps);
	return ps->top == 0;
}

返回栈的数据个数:

int STSize(ST* ps)
{
	assert(ps);
	return ps->top;
}

返回栈顶元素:

STDataType STTop(ST* ps)
{
	assert(ps);
	assert(!STEmpty(ps));
	return ps->a[ps->top - 1];
}

在主函数中打印元素:

int main()
{
	ST ps;
	STInit(&ps);
	STPush(&ps, 1);
	STPush(&ps, 2);
	STPush(&ps, 3);
	STPush(&ps, 4);
	while (!STEmpty(&ps))
	{
		printf("%d ", STTop(&ps));
		STPop(&ps);
	}
	STDestroy(&ps);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值