【数据结构—— 栈的实现(数组栈)】

28 篇文章 0 订阅
8 篇文章 0 订阅

一.栈

1.1栈的概念及结构

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

二.栈的实现

2.1头文件的实现——(Strck.h)

Strck.h
#pragma once

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


typedef int STDataType;
typedef struct Strck
{
	STDataType* a;
	int top; //记录栈顶位置
	int capacity;
}ST;



//初始化/销毁
void STInit(ST* pst);
void STDestroy(ST* pst);

//压栈/出栈
void STPush(ST* pst, STDataType x);
void STPop(ST* pst);
//获取栈顶元素
STDataType STTop(ST* pst);

//判空
bool STEmpty(ST* pst);
//统计栈内元素个数
int STSize(ST* pst);

2.2 源文件的实现——(Strck.c)

Strck.c
#include"Strck.h"


//初始化/销毁
void STInit(ST* pst)
{
	assert(pst);
	pst->a = NULL;
	pst->top = pst->capacity = 0;
}
void STDestroy(ST* pst)
{
	assert(pst);
	free(pst->a);
	pst->a = NULL;
	pst->top = pst->capacity = 0;

}

//压栈/出栈
void STPush(ST* pst, STDataType x)
{
	assert(pst);
	if (pst->top == pst->capacity)
	{
		int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
		STDataType* tmp = (STDataType*)realloc(pst->a, sizeof(STDataType) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		pst->a = tmp;
		pst->capacity = newcapacity;
	}

	pst->a[pst->top] = x;
	pst->top++;
}
void STPop(ST* pst)
{
	assert(pst);
	assert(pst->top > 0);
	pst->top--;
}
//获取栈顶元素
STDataType STTop(ST* pst)
{
	assert(pst);
	assert(pst->top > 0);

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

//判空
bool STEmpty(ST* pst)
{
	assert(pst);

	return pst->top == 0;
}
//统计栈内元素个数
int STSize(ST* pst)
{
	assert(pst);
	return pst->top;
}

2.3 源文件的实现——(test.c)

test.c
#include"Strck.h"


int main()
{
	ST p;
	STInit(&p);

	STPush(&p, 1);
	STPush(&p, 2);
	printf("%d ", STTop(&p));
	STPop(&p);
	STPush(&p, 3);
	STPush(&p, 4);
	printf("%d ", STTop(&p));
	STPop(&p);
	STPush(&p, 5);

	while (!STEmpty(&p))
	{
		printf("%d ", STTop(&p));
		STPop(&p);
	}
	STDestroy(&p);

	return 0;
}

三.栈的实际数据测试展示

1.栈的出栈和入栈的关系是:一对多的关系。
2.元素出入栈满足的方式是:后进先出。

3.1正常的后进先出方式

在这里插入图片描述

3.2 进栈的同时也存在出栈

在这里插入图片描述

  • 22
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 21
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值