【数据结构】栈和队列_数组栈的理解与实现

文章介绍了栈这种数据结构的概念,它是一种后进先出(LIFO)的线性表。栈主要操作包括压栈(插入)、出栈(删除)、返回栈顶元素、获取栈的大小以及判断栈是否为空。栈的实现采用了数组,支持动态扩容,初始化和销毁功能确保了内存的合理使用。
摘要由CSDN通过智能技术生成

前言

栈的实现

前言

栈的概念及结构

:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。 栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。

压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。

出栈:栈的删除操作叫做出栈。出数据也在栈顶

在这里插入图片描述
在这里插入图片描述

栈的实现

栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些。因为数组在尾上插入数据的代价比较小

头文件

#pragma once

#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 StackDestory(ST* ps);
//尾插
void StackPush(ST* ps, STDataType x);
//尾删
void StackPop(ST* ps);
//返回栈顶
STDataType StackTop(ST* ps);
//返回栈大小(数据个数)
int StackSize(ST* ps);
//判断栈是否为空
bool StackEmpty(ST* ps);

初始化栈

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

销毁栈

  • 先把ps->a给free掉后置空
  • 再将capacity和top置为0
void StackDestory(ST* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

尾插

  • 先判断此时数组栈内是否为空或是已满,是则需要先扩容
  • 判断后执行插入,先把值x给数组a再将top++
void StackPush(ST* ps, STDataType x)
{
	assert(ps);
	//是否已满/为空,需扩容
	if (ps->top == ps->capacity)
	{
		//三目即如果为空自动扩充4个,不为空则乘二
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* tmp = realloc(ps->a, sizeof(STDataType) * newCapacity);
		if (tmp == NULL)//判断realloc是否成功
		{
			perror(realloc);
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newCapacity;
	}
	//尾插
	ps->a[ps->top] = x;
	ps->top++;
}

尾删

  • 尾删先断言栈不为空,后直接top–。
void StackPop(ST* ps)
{
	assert(ps);
	//栈不为空
	assert(!StackEmpty(ps));//assert(ps->top > 0);
	ps->top--;
}

返回栈顶

  • 仍先断言,然后直接返回a[ps->top-1],(数组下标-1)
STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	//返回栈顶
	return ps->a[ps->top - 1];
}

返回栈大小(元素个数)

  • 由于每次进行插入删除时都会对ps->top进行相应的增加删除,所以ps->top代表栈的元素个数,直接返回即可
int StackSize(ST* ps)
{
	assert(ps);
	return ps->top;
}

判断栈是否为空

  • bool类型直接返回ps->top == 0即可,如果为空返回true,不为空返回false
bool StackEmpty(ST* ps)
{
	assert(ps);
	return ps->top == 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值