C语言栈的基本操作

1.栈的概念

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

2.顺序栈的实现

2.1顺序栈的头文件及数据类型定义

    

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

typedef int STData_t;

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

   2.2顺序栈的接口函数

//接口 
void StackInit(ST* ps);
void StackDestory(ST* ps);
void StackPush(ST* ps,STData_t x);
void StackPop(ST* ps);
STData_t StackTop(ST* ps);
int StackSize(ST* ps);
bool StackEmpty(ST* ps);

2.3顺序栈的接口函数实现

//初始化 
void StackInit(ST* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->top = 0;	//ps->top = -1   等于0指向栈顶下一个,-1指向栈顶 
 	ps->capacity = 0;
}
//插入数据 
void StackPush(ST* ps,STData_t x)
{
	assert(ps);
	if(ps->capacity == ps->top)
	{
		int newCapaCity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STData_t* temp = realloc(ps->a,sizeof(STData_t) * newCapaCity);
		if(temp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		ps->a = temp;
		ps->capacity = newCapaCity;
	}
	ps->a[ps->top] = x;
	ps->top++; 
}
//对数据进行释放
void StackDestory(ST* ps)
{
	assert(ps);
	free(ps); 
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}
//删除数据 
void StackPop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);
	ps->top--; 
}
//去栈顶数据 
STData_t StackTop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);
	
	return ps->a[ps->top-1]; 
}
//计算元素个数 
int StackSize(ST* ps)
{
	assert(ps);
	return ps->top;
}
//判断是否为空 
bool StackEmpty(ST* ps)
{
	assert(ps);
	/*if(ps->top == 0){
		return true;
	}
	else{
		return false;
	}*/
	
	return ps->top == 0;	
}

2.4测试

//测试 
void TestStack()
{
	ST st;
	StackInit(&st);
	
	StackPush(&st,1);
	StackPush(&st,2);
	StackPush(&st,3);
	StackPush(&st,4);
	
	while(!StackEmpty(&st)) 
	{
		printf("%d ",StackTop(&st));
		StackPop(&st);
	}
	StackDestory(&st);
}

int main()
{
	TestStack(); 
	
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值