和之前实现功能相同,分为一个函数声明文件,函数实现文件,以及测试文件
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int Datatype;
typedef struct stack {
Datatype* a;
int capacity;//空间大小
int top;//栈顶
}ST;
void STInit(ST* ps);//初始化
void STDestroy(ST* ps);//销毁
void STPush(ST* ps, Datatype x);//入栈
void STPop(ST* ps);//出栈
Datatype STTop(ST* ps);//拿出栈顶元素
int STSize(ST* ps);//数组长度
bool STEmpty(ST* ps);//判断是否为空
void STInit(ST* ps)
{
assert(ps);
ps->capacity = 0;
ps->top = 0;
ps->a = NULL;
}
//这里把栈顶初始化为0,入栈后让top++即可
void STDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top=ps->capacity = 0;
}
void STPush(ST* ps, Datatype x)
{
assert(ps);
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
Datatype* tmp = (Datatype*)realloc(ps->a, sizeof(Datatype) * newcapacity);
if (tmp == NULL)
{
perror("realloc failed");
exit(-1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}//这里的realloc规定如果目标空间是空的话,这时相当于malloc创建内存
void STPop(ST* ps)
{
assert(ps);
assert(ps->top > 0);
--ps->top;
}//这里需要判断栈中一个数据都没有的情况
Datatype STTop(ST* ps)
{
assert(ps);
assert(ps->top>0);
return ps->a[ps->top-1];
}//因为top指向的是栈顶的下一个,所以这里需要让top-1
nt STSize(ST* ps)
{
assert(ps);
return ps->top;
}
bool STEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}//这里需要引入<stdbool.h>头文件,判断为真返回frue
以上就是用顺序表实现栈功能的代码讲解,如有错误,欢迎指正,谢谢!