完整代码:
#define _CRT_SECURE_NO_WARINGS 1
//栈的实现
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef struct Stack
{
int* a;
int top;
int capacity;
}ST;
//初始化
void StackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
//插入数据
void StackPush(ST* ps,int x)
{
assert(ps);
//先判断是否满了
if (ps->capacity == ps->top)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
//创建一个临时数组
ST* tmp = (int*)relloc(ps->a, sizeof(int) * newcapacity);
if (tmp == NULL)
{
printd("realloc fail");
exit(-1);
}
else
{
ps->a = tmp;//将tmp给给ps->a
ps->capacity = newcapacity;
}
}
ps->a[ps->top] = x;
ps->top++;
}
//删除数据
void StackPop(ST* ps)
{
assert(ps);
//先判断是否为空才能删除
ps->top--;
}
//判断栈
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
//返回栈顶的元素
int StackTop(ST* ps)
{
assert(ps);
assert(!Empty(ps));
return ps->a[ps->top - 1];
}
//销毁栈
void StackDestory(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
//元素个数
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
void testST()
{
ST ps;
StackInit(&ps);//初始化
StackPush(&ps,1);//插入数据
StackPop(&ps);//删除数据
bool ret = StackEmpty(&ps);//判断是否为空
int ans = StackTop(&ps);//返回栈顶的元素
StackDestory(&ps);
int size = StackSize(&ps);
}
int main()
{
testST();
return 0;
}
如有错误,多多指教!