数据结构 | C语言实现栈

1.Data.h

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int STDataType;
// 支持动态增长的栈
typedef int STDataType;
typedef struct Stack
{
	STDataType* a;
	int top; // 栈顶
	int capacity; // 容量
}ST;

// 初始化栈
//void STInit(ST* ps);
ST* STInit();

// 入栈
void STPush(ST* ps, STDataType data);
// 出栈
void STPop(ST* ps);
// 获取栈顶元素
STDataType STTop(ST* ps);
// 获取栈中有效元素个数
int STSize(ST* ps);
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0 
int STEmpty(ST* ps);
// 销毁栈
void STDestroy(ST* ps);

2.main.cpp

#include"Data.h"
int main()
{
	ST *ps = STInit();
	//初始化方案一:设置返回值,在函数内部通过malloc床架永久结构体,返回结构体指针
	//初始化方案二:不设置返回值,在主函数中创建结构体函数传入指针初始化结构体
	STPush(ps, 1);
	STPush(ps, 2);
	STPush(ps, 3);
	STPush(ps, 4);

	while (ps->top)
	{
		printf("%d ", STTop(ps));
		STPop(ps);
	}
	printf("\n");
	

	return 0;
}

3.Data.cpp

#include"Data.h"
// 初始化栈
//void STInit(ST* ps)
//{
//	assert(ps);
//	ps->a = NULL;
//	ps->top = 0;
//	ps->capacity = 0;
//}

ST* STInit()
{
	ST* newnode = (ST*)malloc(sizeof(ST));
	assert(newnode);
	newnode->a = NULL;
	newnode->top = 0;
	newnode->capacity = 0;
	return newnode;
}

// 入栈
void STPush(ST* ps, STDataType data)
{
	int size = ps->capacity == 0 ? 4 : ps->capacity * 2;
	
	if (ps->top == ps->capacity)
	{
		STDataType* temp = (STDataType*)realloc(ps->a,size*sizeof(ST));
		if (temp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->a = temp;
		ps->capacity = size;
	}

	ps->a[ps->top] = data;
	ps->top++;
}

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

// 获取栈顶元素
STDataType STTop(ST* ps)
{
	assert(ps);
	assert(!STEmpty(ps));

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

// 获取栈中有效元素个数
int STSize(ST* ps)
{
	return ps->top;

}

// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0 
int STEmpty(ST* ps)
{
	assert(ps);

	return ps->top == 0;
}

// 销毁栈
void STDestroy(ST* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	free(ps);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值