![这里写图片描述](https://i-blog.csdnimg.cn/blog_migrate/c12eabbc83db8a8b2e4840e4473f8cb9.png)
Stack.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<assert.h>
#define STACK_INIT_SIZE 100//存储空间初始分配量
#define STACKINCREMENT 10//存储空间分配增量
#define TRUE 1
#define FALSE 0
typedef int DataType;
typedef struct Stack
{
DataType *stack;
int top;
int capacity;
}Stack;
void StackInit(Stack* ps);
void StackDestory(Stack* ps);
void StackPush(Stack* ps, DataType x);
void StackPop(Stack* ps);
DataType StackTop(Stack* ps);
int StackEmpty(Stack* ps);
int StackSize(Stack* ps);
void TestStack();
Stack.c
#include "Stack.h"
void StackInit(Stack * ps)
{
assert(ps);
ps->stack = (DataType*)malloc(sizeof(DataType) * STACK_INIT_SIZE);
ps->top = 0;
ps->capacity = STACK_INIT_SIZE;
}
void StackDestory(Stack * ps)
{
assert(ps);
ps->stack = NULL;
ps->top = -1;
ps->capacity = 0;
}
void StackPush(Stack * ps, DataType x)
{
if (ps->top+1 == ps->capacity)
{
ps->stack = (DataType*)realloc(ps->stack, sizeof(DataType) * STACKINCREMENT);
if (ps->stack == NULL)
{
printf("栈已满,无法插入\n");
}
ps->stack[ps->top++] = x;
}
else
{
ps->stack[++ps->top] = x;
}
}
void StackPop(Stack * ps)
{
assert(ps);
if (ps->top == -1)
{
printf("栈为空,不需要出栈\n");
}
else
{
ps->top--;
}
}
DataType StackTop(Stack * ps)
{
assert(ps);
if (ps->top == 0)
{
return FALSE;
}
else
{
return ps->stack[ps->top];
}
}
int StackEmpty(Stack * ps)
{
assert(ps);
return ps->top == -1 ? TRUE : FALSE;
}
int StackSize(Stack * ps)
{
assert(ps);
return ps->top++;
}