因为栈的功能是先进先出,所以用数组的实现更加方便。
头文件
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top; //栈顶
int capacity; //空间
}ST;
//初始化
void StackInit(ST* ps);
//销毁
void StackDestroy(ST* ps);
//插入数据
void StackPush(ST* ps, STDataType x);
//删除数据
void StackPop(ST* ps);
//提取堆数据
STDataType StackTop(ST* ps);
//判断空
bool StackEmpty(ST* ps);
//判断数据个数
int StackSize(ST* ps);
首先模拟出一个栈
typedef int STDataType;
typedef struct Stack
{
STDataType* a; //数据
int top; //栈顶
int capacity; //空间
}ST;
首先考虑对栈初始化和销毁
void StackInit(ST* ps)
{
ps->a = NULL;
ps->capacity = ps->top = 0;
}
void StackDestroy(ST* ps)
{
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
实现栈的删除和增加,栈只能在数据的一端输入输入。
void StackPush(ST* ps, STDataType x)
{
if (ps->capacity == ps->top)
{
int newcpapcity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = NULL;
tmp = (STDataType*)realloc(ps->a,sizeof(STDataType) * newcpapcity);
if (tmp == NULL)
{
perror(realloc);
exit(-1);
}
ps->a = tmp;
ps->capacity = newcpapcity;
}
ps->a[ps->top] = x;
ps->top++;
}
void StackPop(ST* ps) //
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
STDataType StackTop(ST* ps) //查看栈顶数据
{
assert(ps);
assert(!StackEmpty(ps));
return ps->a[ps->top - 1]; //注意取数据时边界的处理
}
判断是否栈为空,查看数据个数
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0; //判断空
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}