栈C语言实现

栈的概念

栈是一种特殊的线性表,只允许在固定的一段进行插入和删除元素操作。进行数据插入和删除的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFOA(Last In First Out)的原则。
压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作也叫出栈,出数据也在栈顶。
在这里插入图片描述
栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些。因为数组在尾上插入数据的代价比较小

栈的实现

Stack.h

#define  _CRT_SECURE_NO_WARNINGS  1
#pragma once
#include<stdbool.h>
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
 
typedef int STDataType;
 
struct Stack
{
	STDataType* a;
	int top;//栈顶,top指向最后一个数据的下一个位置
	int capacity;//容量,方便增容
};
 
typedef struct Stack Stack;
 
//初始化
void StackInit(Stack* pst);
 
//销毁
void StackDestroy(Stack* pst);
 
//栈顶插入元素
void StackPush(Stack* pst, STDataType x);
 
//栈顶删除元素
void StackPop(Stack* pst);
 
//取栈顶元素
STDataType StackTop(Stack* pst);
 
//判断栈空
bool StackEmpty(Stack* pst);
 
//求栈元素个数
int StackSize(Stack* pst);

Stack.c

#include "039-Stack.h"
 
//初始化
void StackInit(Stack* pst)
{
	assert(pst);
	pst->a = (STDataType*)malloc(sizeof(STDataType) * 4);
	pst->top = 0;
	pst->capacity = 4;
}
 
//销毁
void StackDestroy(Stack* pst)
{
	assert(pst);
	free(pst->a);
	pst->a = NULL;
	pst->capacity = pst->top = 0;
}
 
//插入元素
void StackPush(Stack* pst, STDataType x)
{
	assert(pst);
	if (pst->top == pst->capacity)
	{
		STDataType* tmp = (STDataType*)realloc(pst->a, sizeof(STDataType) * pst->capacity * 2);
		if (tmp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		pst->a = tmp;
		pst->capacity *= 2;
	}
 
	pst->a[pst->top] = x;
	pst->top++;
}
 
//删除元素
void StackPop(Stack* pst)
{
	assert(pst);
	assert(!StackEmpty(pst));
	pst->top--;
}
 
//返回栈顶元素
STDataType StackTop(Stack* pst)
{
	assert(pst);
	assert(!StackEmpty(pst));
	return pst->a[pst->top - 1];
}
 
//判断栈是否已满,空返回1,非空返回0
bool StackEmpty(Stack* pst)
{
	assert(pst);
	return pst->top == 0;
}
 
//求栈中元素个数
int StackSize(Stack* pst)
{
	assert(pst);
	return pst->top;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值