Stack.h
# define _CRT_SECURE_NO_WARNINGS 1
# include <stdio.h>
# include <stdlib.h>
# include <stdbool.h>
# include <assert.h>
typedef int STDateType;
typedef struct Stack
{
STDateType* a;
int top;
int capacity;
} ST;
void STInit ( ST* pst) ;
void STDesTroy ( ST* pst) ;
void STPush ( ST* pst, STDateType x) ;
void STPop ( ST* pst) ;
bool STEmpty ( ST* pst) ;
int STSize ( ST* pst) ;
STDateType STTop ( ST* pst) ;
Stack.c
# include "Stack.h"
void STInit ( ST* pst)
{
assert ( pst) ;
pst-> a = NULL ;
pst-> top = 0 ;
pst-> capacity = 0 ;
}
void STDesTroy ( ST* pst)
{
assert ( pst) ;
free ( pst-> a) ;
pst-> top = pst-> capacity = 0 ;
pst = NULL ;
}
void STPush ( ST* pst, STDateType x)
{
assert ( pst) ;
if ( pst-> top == pst-> capacity)
{
int newcapacity = pst-> capacity == 0 ? 4 : pst-> capacity * 2 ;
STDateType* tmp = ( STDateType* ) realloc ( pst-> a, sizeof ( STDateType) * newcapacity) ;
if ( tmp == NULL )
{
perror ( "realloc fail:" ) ;
exit ( 1 ) ;
}
pst-> capacity = newcapacity;
pst-> a = tmp;
}
pst-> a[ pst-> top] = x;
pst-> top++ ;
}
void STPop ( ST* pst)
{
assert ( pst) ;
assert ( pst-> top > 0 ) ;
pst-> top-- ;
}
bool STEmpty ( ST* pst)
{
assert ( pst) ;
if ( pst-> top != 0 )
return true;
return false;
}
int STSize ( ST* pst)
{
assert ( pst) ;
return pst-> top;
}
STDateType STTop ( ST* pst)
{
assert ( pst) ;
assert ( pst-> top > 0 ) ;
return pst-> a[ pst-> top - 1 ] ;
}
test.c
# include "Stack.h"
void STTest ( )
{
ST pst;
STInit ( & pst) ;
STPush ( & pst, 1 ) ;
STPush ( & pst, 2 ) ;
STPush ( & pst, 3 ) ;
STPush ( & pst, 4 ) ;
STPush ( & pst, 5 ) ;
printf ( "%d " , STTop ( & pst) ) ;
STPop ( & pst) ;
printf ( "%d " , STTop ( & pst) ) ;
STPop ( & pst) ;
bool d = STEmpty ( & pst) ;
if ( d)
{
printf ( "\n不为空\n" ) ;
}
else
{
printf ( "\n为空\n" ) ;
}
int x = STSize ( & pst) ;
printf ( "有%d个元素" , x) ;
STDesTroy ( & pst) ;
}
int main ( )
{
STTest ( ) ;
return 0 ;
}