欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 手游 > 【数据结构】栈的创建

【数据结构】栈的创建

2024/10/24 1:59:37 来源:https://blog.csdn.net/2302_79968411/article/details/142902749  浏览:    关键词:【数据结构】栈的创建

Stack.h

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>//创建栈的结构体
typedef int STDateType;
typedef struct Stack
{STDateType* a;int top;int capacity;
}ST;//栈的初始化
void STInit(ST* pst);//栈的销毁
void STDesTroy(ST* pst);//栈的添加
void STPush(ST* pst, STDateType x);//栈的删除
void STPop(ST* pst);//判断栈是否为空
bool STEmpty(ST* pst);//获取栈中元素的个数
int STSize(ST* pst);//获取栈顶元素
STDateType STTop(ST* pst);

Stack.c

#include"Stack.h"//栈的初始化
void STInit(ST* pst)
{assert(pst);pst->a = NULL;pst->top = 0;pst->capacity = 0;
}//栈的销毁
void STDesTroy(ST* pst)
{assert(pst);free(pst->a);pst->top = pst->capacity = 0;pst = NULL;
}//栈的添加
void STPush(ST* pst, STDateType x)
{assert(pst);//判断是否要开辟空间if (pst->top == pst->capacity){int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;STDateType* tmp = (STDateType*)realloc(pst->a, sizeof(STDateType) * newcapacity);if (tmp == NULL){perror("realloc fail:");exit(1);}pst->capacity = newcapacity;pst->a = tmp;}pst->a[pst->top] = x;pst->top++;
}//栈的删除
void STPop(ST* pst)
{assert(pst);assert(pst->top > 0);pst->top--;
}//判断栈是否为空
bool STEmpty(ST* pst)
{assert(pst);if (pst->top != 0)return true;return false;
}//获取栈中元素的个数
int STSize(ST* pst)
{assert(pst);return pst->top;
}//获取栈顶元素
STDateType STTop(ST* pst)
{assert(pst);assert(pst->top > 0);return pst->a[pst->top - 1];
}

test.c

#include"Stack.h"void STTest()
{ST pst;//栈的初始化STInit(&pst);//入栈STPush(&pst, 1);STPush(&pst, 2);STPush(&pst, 3);STPush(&pst, 4);STPush(&pst, 5);printf("%d ", STTop(&pst));STPop(&pst);printf("%d ", STTop(&pst));STPop(&pst); //判断是否为空bool d = STEmpty(&pst);if (d){printf("\n不为空\n");}else{printf("\n为空\n");}//查询栈中还有几个元素int x = STSize(&pst);printf("有%d个元素", x);//栈的销毁STDesTroy(&pst);
}int main()
{STTest();return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com