stack.h
#pragma once
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int capacity;
int top;
} Stack;
Stack* STCreate();
void STDestroy(Stack* st);
void STPush(Stack* st, STDataType x);
STDataType STPop(Stack* st);
STDataType STTop(Stack* st);
int STSize(Stack* st);
bool STEmpty(Stack* st);
stack.c
#include"Stack.h"
Stack* STCreate()
{
Stack* st = (Stack*)malloc(sizeof(Stack));
if (NULL == st)
{
perror("malloc failed");
exit(-1);
}
st->a = NULL;
st->capacity = st->top = 0;
return st;
}
void STDestroy(Stack* st)
{
assert(st);
free(st->a);
st->a = NULL;
st->capacity = st->top = 0;
free(st);
}
void STPush(Stack* st, STDataType x)
{
assert(st);
if (st->capacity == st->top)
{
int newcapacity = st->capacity == 0 ? 4 : st->capacity * 2;
STDataType* temp = (STDataType*)realloc(st->a, sizeof(STDataType) * newcapacity);
if (NULL == temp)
{
perror("realloc failed");
exit(-1);
}
st->a = temp;
st->capacity = newcapacity;
}
st->a[st->top] = x;
++st->top;
}
STDataType STPop(Stack* st)
{
assert(st);
assert(st->top);
STDataType ret = STTop(st);
--st->top;
return ret;
}
STDataType STTop(Stack* st)
{
assert(st);
assert(st->top);
return st->a[st->top - 1];
}
int STSize(Stack* st)
{
return st->top;
}
bool STEmpty(Stack* st)
{
return st->top == 0;
}
test.c
#include <stdio.h>
#include"Stack.h"
static void STPrint(Stack* st)
{
while (!STEmpty(st))
printf("%d-", STPop(st));
printf("\n");
}
void test1()
{
Stack* st1 = STCreate();
STPush(st1, 4);
STPush(st1, 3);
STPush(st1, 2);
STPush(st1, 1);
STPop(st1);
printf("top = %d\n", STTop(st1));
printf("size = %d\n", STSize(st1));
STPrint(st1);
STDestroy(st1);
}
int main()
{
test1();
return 0;
}