栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

数据结构——栈

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构——栈

  • 什么是栈
  • 创建类型
  • 初始栈
  • 压栈
  • 出栈
  • 察看栈顶的元素
  • 栈的个数
  • 栈是否为空
  • 栈的销毁


什么是栈

栈是一种特殊的线性结构,对数据增加及其删除只能在一端进行操作。
进行数据删除及增加的一端为栈顶,另一端为栈底。
增加数据为压栈。删除数据为出栈。

创建类型
typedef int StackTypeDate;

typedef struct stack
{
	StackTypeDate* arr;
	int top;
	int capacity;
}Stack;
初始栈
void InitStack(Stack* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->top = ps->capacity = 0;
}

压栈

压栈的时候要察看栈是不是满了,以及它为空的情况。

void StackPush(Stack* ps, StackTypeDate x)
{
	assert(ps);

	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		ps->arr = (StackTypeDate*)realloc(ps->arr,sizeof(StackTypeDate) * newcapacity);
		ps->capacity = newcapacity;
	}

	ps->arr[ps->top] = x;
	ps->top++;
}
出栈
void StackPop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	ps->top--;
}
察看栈顶的元素
StackTypeDate StackTop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	return ps->arr[ps->top];
}

栈的个数
int StackSize(Stack* ps)
{
	assert(ps);

	return ps->top;
}

栈是否为空
bool StackEmpty(Stack* ps)
{
	assert(ps);

	return ps->capacity == 0;
}

栈的销毁
void StackDestroy(Stack* ps)
{
	assert(ps);
	free(ps->arr);
	ps->arr = NULL;
	ps->capacity = ps->top = 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/887010.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号