数据结构之栈

发布于:2022-11-28 ⋅ 阅读:(833) ⋅ 点赞:(0)

一、什么是栈

1.栈的概念

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

2.栈的结构

压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据也在栈顶。
在这里插入图片描述

栈的实现

我们今天使用顺序表来实现栈,因为顺序表在尾部插入的时候代价较小。
在这里插入图片描述
在这里插入图片描述

1.结构定义

typedef int STDateType;
typedef struct Stack
{
	STDateType* a;
	int top;
	int capacity;
}ST;

2.栈的初始化

void StackInit(ST* pst);

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

3.压栈

每次在压栈前判断空间是否充足。在第一次给栈4个空间,后续逐步扩大2倍。

void StackPush(ST* pst, STDateType x);

void StackPush(ST* pst, STDateType x)
{
	assert(pst);
	if (pst->capacity == pst->top)
	{
		int NewCapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
		STDateType* tmp = (STDateType*)realloc(pst->a, NewCapacity * sizeof(STDateType));
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		pst->a = tmp;
		pst->capacity = NewCapacity;
	}
	pst->a[pst->top] = x;
	pst->top++;
}

4.出栈

注意判断栈是否为空。

void StackPop(ST* pst);

void StackPop(ST* pst)
{
	assert(pst);
	assert(!StackEmpty(pst));//判断
	pst->top--;
}

5.判断栈是否为空

top为0栈即为空。
在这里插入图片描述

bool StackEmpty(ST* pst);

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

6.访问栈顶数据

top从0开始,注意要减1。
在这里插入图片描述

STDateType StackTop(ST* pst);

STDateType StackTop(ST* pst)
{
	assert(pst);
	assert(!StackEmpty(pst));

	return pst->a[pst->top - 1];
}

7.求栈的大小

在这里插入图片描述
top从0开始,top为多少,栈的大小为多少。

STDateType StackSize(ST* pst);

STDateType StackSize(ST* pst)
{
	assert(pst);
	return pst->top;
}

网站公告

今日签到

点亮在社区的每一天
去签到