我们是用顺序表的结构来实现栈 ,栈是一种数据先进后出,后进先出的数据结构
1.建立头文件
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#pragma warning(disable:4996)
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);//返回元素个数
2.栈的初始化
void StackInit(ST* ps) //初始化
{
assert(ps);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
把a指针指向空,数据个数和容量初始化为0
3.栈的销毁
void StackDestroy(ST* ps) //销毁
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
因为已经为a开辟了空间,所以需要释放
4.栈的数据插入
void StackPush(ST* ps, STdatatype x) //依次插入数据
{
assert(ps);
if (ps->top == ps->capacity)
{
int newca = ps->capacity == 0 ? 4 : ps->capacity * 2;
STdatatype* tmp = (STdatatype*)realloc(ps->a, newca * sizeof(STdatatype));
if (tmp == NULL)
{
perror("realloc fail");
exit(-1);
}
ps->a = tmp;
ps->capacity = newca;
}
ps->a[ps->top] = x;
ps->top++;
}
首先判断容量是否充足,如果已经满容量,先进行扩容。然后让a指向新开辟的空间,让容量大小变成newca,最后在ps->top位置插入x,然后top++。
5.删除栈顶的数据
void StackPop(ST* ps) //删除栈顶端的数据
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
首先判断ps,以及ps是否为空,然后直接top--。
6.返回栈顶的数据
STdatatype StackTop(ST* ps) //返回栈顶的数据
{
assert(ps);
assert(!StackEmpty(ps));
return ps->a[ps->top - 1];
}
7.判断栈是否为空
bool StackEmpty(ST* ps) //判断是否为空
{
assert(ps);
return ps->top == 0;
}
8.返回元素个数
int StackSize(ST* ps) //计算数据数量
{
assert(ps);
return ps->top;
}
9.测试栈
void test()
{
ST st;
StackInit(&st);
StackPush(&st,1); //插入1
StackPush(&st, 2); //插入2
StackPush(&st, 3); //插入3
printf("%d \n", StackTop(&st)); //打印3
StackPop(&st); //删除3
printf("%d \n", StackTop(&st)); //打印2
StackPop(&st); //删除2
StackPush(&st, 4); //插入4
StackPush(&st, 5); //插入5
while (!StackEmpty(&st)) //只要栈不为空就一直打印栈顶元素 并删除栈顶元素
{
printf("%d ", StackTop(&st));
StackPop(&st);
}
printf("\n");
}
int main()
{
test();
return 0;
}
最后为测试结果