Stack.h
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>
#include<stdbool.h>
typedef int STDataType;
//定义栈的结构
typedef struct Stact
{
STDataType* arr;
int capacity;//栈的空间大小
int top; //栈顶
}ST;
//初始化
void STInit(ST* ps);
//销毁
void STDesTroy(ST* ps);
//栈顶---入数据、出数据
void StackPush(ST* ps, STDataType x);
void StackPop(ST* ps);
//取栈顶元素
STDataType StackTop(ST* ps);
bool StackEmpty(ST* ps);
//获取栈中有效元素个数
int STSize(ST* ps);
Stack.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"Stack.h"
//初始化
void STInit(ST* ps)
{
assert(ps);
ps->arr = NULL;
ps->capacity = ps->top = 0;
}
//销毁
void STDesTroy(ST* ps)
{
assert(ps);
if (ps->arr)
{
free(ps->arr);
ps->arr = NULL;
ps->capacity = ps->top = 0;
}
}
//栈顶入数据、出数据
void StackPush(ST* ps, STDataType x)
{
assert(ps);
//判断空间够不够
if (ps->capacity == ps->top)
{
int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
STDataType* tmp = (STDataType*)realloc(ps->arr, newCapacity * sizeof(STDataType));
if (tmp == NULL)
{
perror("relloc fail!");
}
else
{
ps->capacity = newCapacity;
ps->arr = tmp;
}
}
//空间足够
ps->arr[ps->top++] = x;
}
//出数据
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
--ps->top;
}
//判断栈是否为空
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
//取栈顶元素
STDataType StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->arr[ps->top - 1];
}
//获取栈中有效元素个数
int STSize(ST* ps)
{
assert(ps);
return ps->top;
}
test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"Stack.h"
void STTest()
{
ST st;
STInit(&st);
StackPush(&st, 1);
StackPush(&st, 2);
StackPush(&st, 3);
StackPush(&st, 4);
StackPush(&st, 5);
printf("size: %d\n", STSize(&st));
while (!StackEmpty(&st))
{
STDataType data = StackTop(&st);
printf("%d ", data);
//出栈
StackPop(&st);
}
printf("size: %d\n", STSize(&st));
STDesTroy(&st);
}
int main()
{
STTest();
return 0;
}