Stack.h
#pragma once
typedef int DataType;
typedef struct Stack
{
DataType* array;
int capacity;
int size;
}Stack;
void StackInit(Stack* ps);
void StackPush(Stack* ps, DataType data);
void StackPop(Stack* ps);
DataType StackTop(Stack* ps);
int StackSize(Stack* ps);
int StackEmpty(Stack* ps);
void StackDestroy(Stack* ps);
Stack.c
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include "Stack.h"
void StackInit(Stack* ps)
{
assert(ps);
ps->array = (DataType*)malloc(sizeof(DataType)*3);
if(NULL == ps->array)
{
assert(0);
return;
}
ps->capacity = 3;
ps->size = 0;
}
void CheckCapacity(Stack* ps)
{
assert(ps);
if(ps->size == ps->capacity)
{
ps->array = (DataType*)realloc(ps->array, sizeof(DataType) * ps->capacity*2);
if(NULL == ps->array)
{
assert(0);
return;
}
ps->capacity *= 2;
}
}
void StackPush(Stack* ps, DataType data)
{
assert(ps);
CheckCapacity(ps);
ps->array[ps->size++] = data;
}
void StackPop(Stack* ps)
{
assert(ps);
if(StackEmpty(ps))
return;
ps->size--;
}
DataType StackTop(Stack* ps)
{
assert(ps && !StackEmpty(ps));
return ps->array[ps->size-1];
}
int StackSize(Stack* ps)
{
assert(ps);
return ps->size;
}
int StackEmpty(Stack* ps)
{
assert(ps);
return 0 == ps->size;
}
void StackDestroy(Stack* ps)
{
assert(ps);
if(ps->array)
{
free(ps->array);
ps->array = NULL;
ps->capacity = 0;
ps->size = 0;
}
}
test.c
#include <stdio.h>
#include "Stack.h"
int main()
{
Stack s;
StackInit(&s);
StackPush(&s,1);
StackPush(&s,2);
StackPush(&s,3);
StackPush(&s,4);
StackPush(&s,5);
StackPush(&s,6);
StackPush(&s,7);
printf("size = %d\n", StackSize(&s));
printf("top = %d\n", StackTop(&s));
StackPop(&s);
StackPop(&s);
printf("size = %d\n", StackSize(&s));
printf("top = %d\n", StackTop(&s));
return 0;
}