c实现栈的功能

因为栈的功能是先进先出,所以用数组的实现更加方便。

头文件

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int STDataType;
typedef struct Stack
{
	STDataType* a;
	int top;				//栈顶
	int capacity;			//空间
}ST;

//初始化
void StackInit(ST* ps);
//销毁
void StackDestroy(ST* ps);
//插入数据
void StackPush(ST* ps, STDataType x);
//删除数据
void StackPop(ST* ps);
//提取堆数据
STDataType StackTop(ST* ps);
//判断空
bool StackEmpty(ST* ps);
//判断数据个数
int StackSize(ST* ps);

首先模拟出一个栈

typedef int STDataType;
typedef struct Stack
{
	STDataType* a;          //数据
	int top;				//栈顶
	int capacity;			//空间
}ST;

首先考虑对栈初始化和销毁

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




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

实现栈的删除和增加,栈只能在数据的一端输入输入

void StackPush(ST* ps, STDataType x)
{
	if (ps->capacity == ps->top)
	{
		int newcpapcity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* tmp = NULL;
		tmp = (STDataType*)realloc(ps->a,sizeof(STDataType) * newcpapcity);
		if (tmp == NULL)
		{
			perror(realloc);
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newcpapcity;
	}
	ps->a[ps->top] = x;
	ps->top++;

}

void StackPop(ST* ps)			//
{
	assert(ps);
	assert(!StackEmpty(ps));		
	ps->top--;
}


STDataType StackTop(ST* ps)        //查看栈顶数据
{
	assert(ps);
	assert(!StackEmpty(ps));

	return ps->a[ps->top - 1];    //注意取数据时边界的处理
}

判断是否栈为空,查看数据个数

bool StackEmpty(ST* ps)
{
	assert(ps);
	return ps->top == 0;			//判断空
}

int StackSize(ST* ps)
{
	assert(ps);

	return ps->top;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值