test.c
#include "Stack.h"
void test_1()
{
Stack st;
InitStack(&st);
PushStack(&st, 1);
PushStack(&st, 2);
PushStack(&st, 3);
PushStack(&st, 4);
PrintfStack(&st);
DestroyStack(&st);
}
int main()
{
test_1();
return 0;
}
Stack.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
typedef int DataType;
typedef struct Stack
{
DataType* ret;
int top;
int capacity;
}Stack;
void InitStack(Stack* ps);
void DestroyStack(Stack* ps);
void PushStack(Stack* ps, DataType n);
void PopStack(Stack* ps);
DataType TopStack(Stack* ps);
int SizeStack(Stack* ps);
bool EmptyStack(Stack* ps);
void PrintfStack(Stack* ps);
Stack.c
#include "Stack.h"
void InitStack(Stack* ps)
{
assert(ps);
ps->ret = NULL;
ps->top = 0;
ps->capacity = 0;
}
void DestroyStack(Stack* ps)
{
assert(ps);
free(ps->ret);
ps->ret = NULL;
ps->top = 0;
ps->capacity = 0;
}
void PushStack(Stack* ps, DataType n)
{
assert(ps);
if (ps->top == ps->capacity)
{
int NewCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
DataType* tmp = realloc(ps->ret, sizeof(DataType) * NewCapacity);
if (NULL == tmp)
{
perror(tmp);
exit(-1);
}
ps->ret = tmp;
ps->capacity = NewCapacity;
}
ps->ret[ps->top] = n;
ps->top++;
}
void PopStack(Stack* ps)
{
assert(ps);
assert(!EmptyStack(ps));
ps->top--;
}
DataType TopStack(Stack* ps)
{
assert(ps);
assert(!EmptyStack(ps));
return ps->ret[ps->top - 1];
}
int SizeStack(Stack* ps)
{
assert(ps);
return ps->top;
}
bool EmptyStack(Stack* ps)
{
return ps->top == 0;
}
void PrintfStack(Stack* ps)
{
assert(ps);
assert(!EmptyStack(ps));
while (ps->top)
{
printf("%d ", TopStack(ps));
PopStack(ps);
}
printf("\n");
}