栈详解 顺序栈 基本操作 C语言实现 数据结构

一、栈

1.1栈的概念及结构

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

 1.2栈的实现

栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些,因为数组在尾上插入数据的代价比较小

顺序栈基本操作 

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int STDataType;
typedef struct stack
{
	STDataType* a;
	int top;
	int capacity;
}stack;

1)顺序栈初始化

void StackInit(stack* ps)//初始化
{
	assert(ps != NULL);
	ps->a = NULL;
	ps->top = 0;
	ps->capacity = 0;
}

 2)顺序栈销毁

void StackDestroy(stack* ps)//销毁
{
	assert(ps != NULL);
	free(ps->a);
	ps->a = NULL;
	ps->top = ps->capacity=0;
}

3)顺序栈入栈

void StackPush(stack* ps, STDataType x)//入栈
{
	assert(ps != NULL);
	if (ps->top == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType)*newcapacity);
		if (tmp == NULL)
		{
			exit(1);
		}
		ps->a = tmp;
		ps->capacity = newcapacity;
	}
	ps->a[ps->top] = x;
	ps->top++;
}

 4)顺序栈判空

bool StackEmpty(stack* ps)//判断栈是否为空
{
	assert(ps != NULL);
	return ps->top==0;
}

5)顺序栈出栈

void StackPop(stack* ps)//出栈
{
	assert(ps != NULL);
	assert(!StackEmpty(ps));
	ps->top--;
}

6)取栈顶元素

STDataType Stacktop(stack* ps)//取栈顶元素
{
	assert(ps != NULL);
	assert(!StackEmpty(ps));
	return ps->a[ps->top - 1];
}

7)元素个数

int StackSize(stack* ps)//元素个数
{
	assert(ps != NULL);
	return ps->top;
}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值