1.Data.h
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int STDataType;
// 支持动态增长的栈
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top; // 栈顶
int capacity; // 容量
}ST;
// 初始化栈
//void STInit(ST* ps);
ST* STInit();
// 入栈
void STPush(ST* ps, STDataType data);
// 出栈
void STPop(ST* ps);
// 获取栈顶元素
STDataType STTop(ST* ps);
// 获取栈中有效元素个数
int STSize(ST* ps);
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int STEmpty(ST* ps);
// 销毁栈
void STDestroy(ST* ps);
2.main.cpp
#include"Data.h"
int main()
{
ST *ps = STInit();
//初始化方案一:设置返回值,在函数内部通过malloc床架永久结构体,返回结构体指针
//初始化方案二:不设置返回值,在主函数中创建结构体函数传入指针初始化结构体
STPush(ps, 1);
STPush(ps, 2);
STPush(ps, 3);
STPush(ps, 4);
while (ps->top)
{
printf("%d ", STTop(ps));
STPop(ps);
}
printf("\n");
return 0;
}
3.Data.cpp
#include"Data.h"
// 初始化栈
//void STInit(ST* ps)
//{
// assert(ps);
// ps->a = NULL;
// ps->top = 0;
// ps->capacity = 0;
//}
ST* STInit()
{
ST* newnode = (ST*)malloc(sizeof(ST));
assert(newnode);
newnode->a = NULL;
newnode->top = 0;
newnode->capacity = 0;
return newnode;
}
// 入栈
void STPush(ST* ps, STDataType data)
{
int size = ps->capacity == 0 ? 4 : ps->capacity * 2;
if (ps->top == ps->capacity)
{
STDataType* temp = (STDataType*)realloc(ps->a,size*sizeof(ST));
if (temp == NULL)
{
perror("realloc fail");
return;
}
ps->a = temp;
ps->capacity = size;
}
ps->a[ps->top] = data;
ps->top++;
}
// 出栈
void STPop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
ps->top--;
}
// 获取栈顶元素
STDataType STTop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
return ps->a[ps->top - 1];
}
// 获取栈中有效元素个数
int STSize(ST* ps)
{
return ps->top;
}
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int STEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
// 销毁栈
void STDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
free(ps);
}