数据结构之栈的实现(含全部代码)
栈的实现
实现栈所需要的头文件
#pragma once#include#include#include#include
定义数据类型以及创建栈
typedef int STDataType;typedef struct Stack{STDataType* a;int top;int capacity;//容量}ST;
栈所需要实现的函数
//初始化void StackInit(ST* ps);//销毁栈void StackDestory(ST* ps);//入栈void StackPush(ST* ps, STDataType x);//出栈void StackPop(ST* ps);//取值STDataType StackTop(ST* ps);//计算个数int StackSize(ST* ps);//判断栈是否为空bool StackEmpty(ST* ps);
函数的实现
#include"Stack.h"typedef int STDataType;void StackInit(ST* ps){assert(ps);ps->a = (STDataType*)malloc(sizeof(STDataType) * 4);if (ps->a == NULL){printf("malloc fail\n");exit(-1);}else{ps->capacity = 4;ps->top = 0;}}void StackDestory(ST* ps){assert(ps);free(ps->a);ps->a = NULL;ps->capacity = ps->top = 0;}void StackPush(ST* ps, STDataType x){assert(ps);//判断是否增容if (ps->top == ps->capacity){STDataType* tmp = (STDataType*)realloc(ps->a, ps->capacity * 2 * sizeof(STDataType));if (tmp == NULL){printf("realloc fail\n");exit(-1);}else{ps->a = tmp;ps->capacity *= 2;}}ps->a[ps->top] = x;ps->top++;}void StackPop(ST* ps){assert(ps);assert(ps->top > 0);ps->top--;}STDataType 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);return ps->top == 0;}