实现栈的各种基本运算的算法(数据结构)

栈的特点是先入后出,后进先出。

(1)静态栈的创建

//静态栈

#define 10 N
#define int STDataType

typedef struct ST{
    STDataType a[N];
    int top;//栈顶元素
}Stack;

(2)动态栈的创建(本文代码基于动态栈)

//动态栈
#define int STDataType

typedef struct ST {
	STDataType* _a;
	int _top;//栈顶元素
	int _capacity;//最大容量
}Stack;

(3)初始化栈

//初始化栈
void StackInit(Stack* pst)
{
	assert(pst);
	pst->_a = NULL;
	pst->_top = 0;
	pst->_capacity = 0;
}

(4)入栈

//入栈
void StackPush(Stack* pst, STDataType x)
{
	assert(pst);
	if (pst->_top == pst->_capacity)
	{
		STDataType newcapacity = pst->_capacity == 0 ? 4 : (pst->_capacity * 2);
		STDataType* temp = (STDataType*)realloc(pst->_a, sizeof(STDataType) * newcapacity);
		if (temp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		pst->_a = temp;
		pst->_capacity = newcapacity;
	}
	pst->_a[pst->_top] = x;
	pst->_top++;
}

(5)出栈

//出栈
void StackPop(Stack* pst)
{
	assert(pst);
	assert(pst->_top > 0);
	pst->_top--;
}

(6)获取栈顶元素

//获取栈顶元素
STDataType StackTop(Stack* pst)
{
	assert(pst);
	assert(pst->_top>0);
	return pst->_a[pst->_top-1];
}

(7)获取栈的有效个数

//出栈
void StackPop(Stack* pst)
{
	assert(pst);
	assert(pst->_top > 0);
	pst->_top--;
}

(8)判断栈是否为空

//判断栈是否为空,是返回1,非空返回0
bool StackEmpty(Stack* pst)
{
	assert(pst);
	if (pst->_top == 0)
		return true;
	else
		return false;
}

(9)打印栈

//打印栈
void StackPrint(Stack* pst)
{
	while (!StackEmpty(pst))
	{
		printf("%d\n", StackTop(pst));
		StackPop(pst);
	}
}

(10)销毁栈

//销毁栈
void StackDestory(Stack* pst)
{
	assert(pst);
	free(pst->_a);
	pst->_a = NULL;
	pst->_top = pst->_capacity = 0;
}

相关推荐

  1. 实现各种基本运算算法数据结构

    2024-04-14 14:32:03       43 阅读
  2. 实现队列各种基本运算算法数据结构

    2024-04-14 14:32:03       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-14 14:32:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-14 14:32:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-14 14:32:03       82 阅读
  4. Python语言-面向对象

    2024-04-14 14:32:03       91 阅读

热门阅读

  1. 北斗导航 | 北斗三号区域短报文服务解析

    2024-04-14 14:32:03       39 阅读
  2. Linux和Windows的主要区别

    2024-04-14 14:32:03       40 阅读
  3. SpringCloudAlibaba-整合openfeign和loadbalence(三)

    2024-04-14 14:32:03       35 阅读
  4. 多汗症的物理治疗有哪些?

    2024-04-14 14:32:03       33 阅读
  5. 关系网络(c++题解)

    2024-04-14 14:32:03       30 阅读
  6. AspectJ框架实现AOP简介

    2024-04-14 14:32:03       36 阅读