Data Structure - Array Stack (C)
分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net
/*
* Fatal.h - by FreeMan
*/
#include <stdio.h>
#include <stdlib.h>
#define Error( Str ) FatalError( Str )
#define FatalError( Str ) fprintf( stderr, "%s\n", Str ), exit( 1 )
/*
* ArStack.h - by FreeMan
*/
typedef int ElementType;
#ifndef _ArStack_H_
#define _ArStack_H_
struct ArStackRecord;
typedef struct ArStackRecord *ArStack;
int IsArStackEmpty(ArStack S);
int IsArStackFull(ArStack S);
ArStack CreateArStack(int MaxElements);
void DisposeArStack(ArStack S);
void MakeArStackEmpty(ArStack S);
void PushArStack(ElementType X, ArStack S);
ElementType TopOfArStack(ArStack S);
void PopArStack(ArStack S);
ElementType TopAndPopArStack(ArStack S);
#endif
/*
* ArStack.c - by FreeMan
*/
#include "ArStack.h"
#include "..\Fatal.h"
#include <stdlib.h>
#define EmptyTOS ( -1 )
#define MinStackSize ( 5 )
struct ArStackRecord
{
int Capacity;
int TopOfStack;
ElementType *Array;
};
int IsArStackEmpty(ArStack S)
{
return S->TopOfStack == EmptyTOS;
}
int IsArStackFull(ArStack S)
{
return S->TopOfStack == S->Capacity - 1;
}
ArStack CreateArStack(int MaxElements)
{
ArStack S;
if (MaxElements < MinStackSize)
{
Error("Stack size is too small!");
}
S = malloc(sizeof(struct ArStackRecord));
if (S == NULL)
{
FatalError("Out of memory!!");
}
S->Array = malloc(sizeof(ElementType) * MaxElements);
if (S->Array == NULL)
{
FatalError("Out of memory!!");
}
S->Capacity = MaxElements;
MakeArStackEmpty(S);
return S;
}
void MakeArStackEmpty(ArStack S)
{
S->TopOfStack = EmptyTOS;
}
void DisposeArStack(ArStack S)
{
if (S != NULL)
{
free(S->Array);
free(S);
}
}
void PushArStack(ElementType X, ArStack S)
{
if (IsArStackFull(S))
{
Error("Full stack!");
}
else
{
S->Array[++S->TopOfStack] = X;
}
}
ElementType TopOfArStack(ArStack S)
{
if (!IsArStackEmpty(S))
{
return S->Array[S->TopOfStack];
}
Error("Empty stack!");
return 0;
}
void PopArStack(ArStack S)
{
if (IsArStackEmpty(S))
{
Error("Empty stack!");
}
else
{
S->TopOfStack--;
}
}
ElementType TopAndPopArStack(ArStack S)
{
if (!IsArStackEmpty(S))
{
return S->Array[S->TopOfStack--];
}
Error("Empty stack!");
return 0;
}
/*
* ArStackTest.c - by FreeMan
*/
#include "ArStack.h"
#include <stdio.h>
main()
{
ArStack S;
int i;
S = CreateArStack(12);
for (i = 0; i < 10; i++)
{
PushArStack(i, S);
}
while (!IsArStackEmpty(S))
{
printf("%d\n", TopOfArStack(S));
PopArStack(S);
}
DisposeArStack(S);
return 0;
}
// Output:
/*
9
8
7
6
5
4
3
2
1
0
*/
还没有评论,来说两句吧...