自学内容网 自学内容网

数据结构(栈及其实现)

概念与结构

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

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

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;
}

结尾

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


原文地址:https://blog.csdn.net/2406_83947720/article/details/140594212

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!