数据结构(栈及其实现)

概念与结构

栈:⼀种特殊的线性表,其只允许在固定的⼀端进⾏插⼊和删除元素操作。

进⾏数据插⼊和删除操作的⼀端称为栈顶,另⼀端称为栈底。栈中的数据元素遵守后进先出

LIFO(Last In First Out)的原则。

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

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

栈底层结构选型

栈的实现⼀般可以使⽤数组或者链表实现,相对⽽⾔数组的结构实现更优⼀些。因为数组在尾上插⼊ 数据的代价⽐较⼩。

栈的实现

Stack.h

其中包含的各种声明已在代码中注释,此处不在赘述。

#pragma once

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>

//定义栈的结构
typedef int STDataType;
typedef struct Stack
{
	STDataType* arr;
	int capacity;     //栈的空间大小
	int top;          //栈顶
}ST;

void STInit(ST* ps);
void STDestroy(ST* ps);

//栈顶---入数据、出数据
void StackPush(ST* ps, STDataType x);
void StackPop(ST* ps);

//取栈顶元素
STDataType StackTop(ST* ps);

bool StackEmpty(ST* ps);

//获取栈中有效元素个数
int STSize(ST* ps);

Stack.c

该处的代码与头文件中的声明一一对应,大家可以参考参考。

栈的初始化

void STInit(ST* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->capacity = ps->top = 0;
}

栈的销毁

void STDestroy(ST* ps)
{
	assert(ps);
	if (ps->arr)
		free(ps->arr);
	ps->arr = NULL;
	ps->top = ps->capacity = 0;
}

栈的判空

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

入栈

void StackPush(ST* ps, STDataType x)
{
	assert(ps);
	
	//1.判断空间是否足够
	if (ps->capacity == ps->top)
	{
		int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		STDataType* tmp = (STDataType*)realloc(ps->arr, newCapacity * sizeof(STDataType));
		if (tmp == NULL)
		{
			perror("realloc fail!");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newCapacity;
	}
	//空间足够
	ps->arr[ps->top++] = x;
}

出栈

void StackPop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));

	--ps->top;
}

取栈顶元素

//取栈顶元素
STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));

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

获取栈中有效元素个数

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

结尾

以上便是本期的全部内容,感谢大家的支持!

相关推荐

  1. C语言实现基础数据结构——

    2024-07-22 01:30:02       48 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-22 01:30:02       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-22 01:30:02       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-22 01:30:02       45 阅读
  4. Python语言-面向对象

    2024-07-22 01:30:02       55 阅读

热门阅读

  1. vue排序

    2024-07-22 01:30:02       17 阅读
  2. 项目架构图的最佳实践:绘制、维护与示例

    2024-07-22 01:30:02       19 阅读
  3. C++多态

    C++多态

    2024-07-22 01:30:02      19 阅读
  4. Nginx 不转发请求 IP

    2024-07-22 01:30:02       22 阅读
  5. ctfshow web AK杯

    2024-07-22 01:30:02       16 阅读
  6. 正态分布是什么

    2024-07-22 01:30:02       18 阅读
  7. deploy gitlab through docker

    2024-07-22 01:30:02       19 阅读