ST.h
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int STDataType;
typedef struct ST {
STDataType* arr;
int top;
int capacity;
}stack;
void StackInit(stack* ps);//初始化与销毁
void StackDestroy(stack* ps);
void StackPush(stack* ps, STDataType x);//压栈
STDataType StackTop(stack* ps);//获取栈顶元素
void StackPop(stack* ps);//出栈
bool EmptyST(stack* ps);//判断是否为空
int StackSize(stack* ps);//返回栈内元素个数
ST.c
#include"ST.h"
void StackInit(stack* ps)//初始化与销毁
{
ps->arr = NULL;
ps->top = 0;//栈的下一个元素下标,也可以用-1,表示正在栈顶的元素下标
ps->capacity = 0;//空间赋0
}
void StackDestroy(stack* ps)
{
free(ps->arr);
ps->arr = NULL;
ps->capacity = 0;
ps->top = 0;//只销毁了栈的空间,记录栈信息的结构体未销毁
}
void StackPush(stack* ps, STDataType x)//压栈
{
assert(ps);//检查记录栈的变量不为空
//不用单独写判断空间申请空间的函数
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;//新空间容量,为0或几倍
STDataType* newarr = (STDataType*)realloc(ps->arr, sizeof(STDataType) * newcapacity); //新定义变量接受,防止realloc返回空指针导致原指针接受,空间丢失
assert(newarr);
ps->arr = newarr;//接受新空间,老空间已经被realloc释放了
ps->capacity = newcapacity;//记录空间变化
}
ps->arr[ps->top] = x;
ps->top++;
}
//获取栈顶数据,去除顶在一起是出栈
STDataType StackTop(stack* ps)//获取栈顶元素
{
assert(ps);
assert(ps->top);
return ps->arr[ps->top - 1];
}
void StackPop(stack* ps)//去顶
{
assert(ps);
assert(ps->top);//栈不为空
ps->top--;
}
bool EmptyST(stack* ps)//判断是否为空
{
assert(ps);
return !ps->top;
}
int StackSize(stack* ps)//返回栈内元素个数
{
assert(ps);
return ps->top - 1;
}
main.c
#include"ST.h"
int main()
{
stack x;
StackInit(&x);
StackPush(&x, 1);
StackPush(&x, 2);
StackPush(&x, 3);
StackPush(&x, 4);
StackPush(&x, 5);
while (!EmptyST(&x))
{
printf("%d ", StackTop(&x));
StackPop(&x);
}
printf("\n");
StackDestroy(&x);
return 0;
}