数据结构之栈(C语言)

本文详细介绍了栈的基本概念,包括栈的定义、栈的建立过程(使用C语言实现),涉及栈的初始化、入栈、出栈、获取栈顶元素、检查栈是否为空以及栈的销毁等操作。
摘要由CSDN通过智能技术生成

一、什么是栈

 是只允许在一端进行插入或删除的线性表。首先栈是一种线性表,但限定这种线性表只能在某一端进行插入和删除操作。

 二.、栈的建立

2.1 包含的标准库

   #include <stdio.h>
   #include <assert.h>
   #include<stdlib.h>
   #include<stdbool.h>
2.2 定义结构体
typedef int STDataType;
typedef struct Stack
{
	STDataType* a;
	int top;
	int capacity;
}Stack;

2.3 函数声明

//栈初始化
void StackInit(Stack* ps);
//入栈
void StackPush(Stack* ps);
//出栈
void StackPop(Stack* ps);
//获取栈顶元素
STDataType StackTop(Stack* ps);
//获取栈中有效元素
int StackSize(Stack* ps);
//检测栈是否为空,如果为空返回非零结果,如果不为空返回0
bool StackEmpty(Stack* ps);
//栈的销毁
void StackDestroy(Stack* ps);

2.4 函数的实现

1.栈的初始化

top=0定义为栈顶元素的下一位下标   也可以定义为-1   capacity表示当前栈的容量

void StackInit(Stack* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->top = 0;
	ps->capacity = 0;
}
2.入栈操作
void StackPush(Stack* ps, STDataType x)
{
	assert(ps);
	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity*2;
		STDataType* tmp = (STDataType*)realloc(ps->a, newcapacity * sizeof(STDataType));
		if (tmp == NULL)
		{
			
			perror("realloc fail");
			return;
		}
		ps->a = tmp;
		ps->capacity = newcapacity;
	}
	ps->a[ps->top++] = x;
}
3.出栈操作
void StackPop(Stack* ps)
{
	assert(ps);
	if (ps->top == 0)
	{
		printf("栈内已无元素,出栈失败");
		exit(-1);
	}
	ps->top--;
}
4.获取栈顶元素
STDataType StackTop(Stack* ps)
{
	assert(ps);
	if (ps->top == 0)
	{
		printf("栈内已无元素,获取栈顶元素失败");
		exit(-1);
	}
	return ps->a[ps->top-1];
}
5.获取栈中有效元素个数
int StackSize(Stack* ps)
{
	assert(ps);
	return ps->top;
}
6.检测栈是否为空,如果为空返回非零结果,如果不为空返回0
bool StackEmpty(Stack* ps)
{
	assert(ps);
	if (ps->top == -1)
	{
		return true;
	}
	else
	{
		return false;
	}
}
 7.栈的销毁
void StackDestroy(Stack* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->top = -1;
	ps->capacity = 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值