Test.c
# define _CRT_SECURE_NO_WARNINGS 1
# include "Stack.h"
void TestStack ( )
{
ST st;
StackInit ( & st) ;
StackPush ( & st, 1 ) ;
StackPush ( & st, 2 ) ;
StackPush ( & st, 3 ) ;
StackPush ( & st, 4 ) ;
StackPush ( & st, 5 ) ;
while ( ! StackEmpty ( & st) )
{
printf ( "%d " , StackTop ( & st) ) ;
StackPop ( & st) ;
}
printf ( "\n" ) ;
StackDestory ( & st) ;
}
int main ( )
{
TestStack ( ) ;
return 0 ;
}
Stack.h
# define _CRT_SECURE_NO_WARNINGS 1
# pragma once
# include <stdio.h>
# include <stdlib.h>
# include <assert.h>
# include <stdbool.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
} ST;
void StackInit ( ST* ps) ;
void StackDestory ( ST* ps) ;
void StackPush ( ST* ps , STDataType x) ;
void StackPop ( ST* ps) ;
STDataType StackTop ( ST* ps) ;
bool StackEmpty ( ST* ps) ;
int StackSize ( ST* ps) ;
Stack.c
# define _CRT_SECURE_NO_WARNINGS 1
# include "Stack.h"
void StackInit ( ST* ps)
{
assert ( ps) ;
ps-> a = NULL ;
ps-> top = 0 ;
ps-> capacity = 0 ;
}
void StackDestory ( ST* ps)
{
assert ( ps) ;
free ( ps-> a) ;
ps-> a = NULL ;
ps-> top = ps-> capacity = 0 ;
}
void StackPush ( ST* ps, STDataType x)
{
assert ( ps) ;
if ( ps-> top == ps-> capacity)
{
int newcapacity = ( ps-> capacity == 0 ) ? 4 : ps-> capacity * 2 ;
STDataType* tmp = ( STDataType* ) realloc ( ps-> a, sizeof ( STDataType) * newcapacity) ;
if ( NULL == tmp)
{
printf ( "realloc fail\n" ) ;
exit ( - 1 ) ;
}
ps-> a = tmp;
ps-> capacity = newcapacity;
}
ps-> a[ ps-> top] = x;
ps-> top++ ;
}
void StackPop ( ST* ps)
{
assert ( ps) ;
assert ( ! StackEmpty ( ps) ) ;
ps-> top-- ;
}
STDataType StackTop ( ST* ps)
{
assert ( ps) ;
assert ( ! StackEmpty ( ps) ) ;
return ( ps-> a[ ps-> top- 1 ] ) ;
}
bool StackEmpty ( ST* ps)
{
assert ( ps) ;
return ( ps-> top == 0 ) ;
}
int StackSize ( ST* ps)
{
assert ( ps) ;
return ps-> top;
}