栈的基本内容实现(c语言)

第一步

在vs的头文件中选择建立文件stack.h,接着创建一系列的头文件

​
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int StackData;
typedef struct stack
{
	StackData* a;
	int top;
	int capacity;
}ST;

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

// 入栈  出栈
void STPush(ST* pst, StackData x);
void STPop(ST* pst);

// 取栈顶数据
StackData STTop(ST* pst);

// 判空
bool STEmpty(ST* pst);
// 获取数据个数
int STSize(ST* pst);

​

第二步

在源文件中创建stack.c文件

栈的创立和销毁我就不多赘述(记得要在stack.c中引用stack.h,只能使用"",不可使用<>来引用)

#include"stack.h"
void STInit(ST* pst)//栈的初始化
{
	assert(pst);
	pst->a = NULL;
	pst->capacity = pst->top = 0;
}
void STDestory(ST* pst)//栈的销毁
{ 
	assert(pst->a);
	    free(pst->a);
		pst->a = NULL;
		pst->capacity = pst->top = 0;
}

接下来的重点是入栈与扩容,即当空间满时我们应该选择扩大a的空间。

   1.首先我们需要先判断pst是否为空,assert函数为判断函数。

    2.接着我们需要判断top的值是否与capacity相等,如若相等则进行下一步

    3.使用malloc函数进行扩容,一般扩大原capacity的两倍

  

void STPush(ST* pst, StackData x)//入栈
{
	assert(pst);
	// 扩容
	if (pst->top == pst->capacity)
	{
		int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
		StackData* tmp = (StackData*)realloc(pst->a, newcapacity * sizeof(StackData));
		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);
	int a = pst->top;
	pst->top--;
}
StackData STTop(ST* pst)//取栈顶元素
{
	assert(pst);
	assert(pst->a);
	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;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值