代码如下:
Stack.h
#pragma once
// 支持动态增长的栈
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top; // 栈顶
int capacity; // 容量
}Stack;
// 初始化栈
void StackInit(Stack* ps);
// 入栈
void StackPush(Stack* ps, STDataType data);
// 出栈
void StackPop(Stack* ps);
// 获取栈顶元素
STDataType StackTop(Stack* ps);
// 获取栈中有效元素个数
int StackSize(Stack* ps);
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int StackEmpty(Stack* ps);
// 销毁栈
void StackDestroy(Stack* ps);
Stack.c
#include "Stack.h"
// 初始化栈
void StackInit(Stack* ps)
{
assert(ps);
ps->a = NULL;//可开可不开
ps->top = 0;//top初始化为0或者-1都可以,只是a[ps->top]的意义有区别,这里top指向栈顶的下一个位置,也可以看做栈里的元素个数
ps->capacity = 0;
}
// 入栈
void StackPush(Stack* ps, STDataType data)
{
assert(ps);
if (ps->top == ps->capacity)//空间已满
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;//容量为0则初始开辟4个空间,如果不为0则2倍扩容
STDataType* tmp = (STDataType*)realloc(ps->a,sizeof(STDataType) * newcapacity);
if (NULL == tmp)//扩容失败的情况
{
perror("realloc fail!");
return;
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top++] = data;
}
// 出栈
void StackPop(Stack* ps)
{
assert(ps);
assert(ps->top > 0);//
ps->top--;
}
// 获取栈顶元素
STDataType StackTop(Stack* ps)
{
assert(ps);
assert(ps->top > 0);
return ps->a[ps->top - 1];
}
// 获取栈中有效元素个数
int StackSize(Stack* ps)
{
assert(ps);
return ps->top;
}
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int StackEmpty(Stack* ps)
{
assert(ps);
//if (0 == ps->top)
// return 1;
//else
// return 0;
return ps->top == 0;
}
// 销毁栈
void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
test.c
#include "Stack.h"
void StackTest()
{
Stack ST;
StackInit(&ST);
StackPush(&ST, 1);
StackPush(&ST, 2);
StackPush(&ST, 3);
StackPush(&ST, 4);
StackPush(&ST, 5);//1,2,3,4,5
printf("栈顶元素是 %d \n", StackTop(&ST));
printf("栈里一共有 %d 个元素\n", StackSize(&ST));
StackPop(&ST);
StackPop(&ST);
StackPop(&ST);
StackPop(&ST);//不空
if (StackEmpty(&ST))
printf("栈为空\n");
else
printf("栈不为空\n");
StackPop(&ST);//空
if (StackEmpty(&ST))
printf("栈为空\n");
else
printf("栈不为空\n");
StackDestroy(&ST);
}
int main()
{
StackTest();
return 0;
}
运行结果:
通过调试我们可以看见栈的初始化、入栈、出栈和销毁都是成功的
如有错误,欢迎指正.