4.栈的数组实现
fatal.h
#include <stdio.h>
#include <stdlib.h>
#define Error(Str) FatalError(Str)
#define FatalError(Str) fprintf(stderr, "%s\n", Str), exit(1)
stackar.h
typedef int ElementType;
#ifndef _Stack_h
#define _Stack_h
struct StackRecord;
typedef struct StackRecord *Stack;
int IsEmpty(Stack S);
int IsFull(Stack S);
Stack CreateStack(int MaxElements);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
void Push(ElementType X, Stack S);
ElementType Top(Stack S);
void Pop(Stack S);
ElementType TopAndPop(Stack S);
#endif
stackar.c
#include "stackar.h"
#include "fatal.h"
#include <stdlib.h>
#define EmptyTOS ( -1 )
#define MinStackSize ( 5 )
struct StackRecord
{
int Capacity;
int TopOfStack;
ElementType *Array;
};
int IsEmpty(Stack S)
{
return S->TopOfStack == EmptyTOS;
}
int IsFull(Stack S)
{
return S->TopOfStack == S->Capacity - 1;
}
Stack CreateStack(int MaxElements)
{
Stack S;
if (MaxElements < MinStackSize)
Error("Stack size is too small");
S = malloc(sizeof(struct StackRecord));
if (S == NULL)
FatalError("Out of space!!!");
S->Array = malloc(sizeof(ElementType) * MaxElements);
if (S->Array == NULL)
FatalError("Out of space!!!");
S->Capacity = MaxElements;
MakeEmpty(S);
return S;
}
void MakeEmpty(Stack S)
{
S->TopOfStack = EmptyTOS;
}
void DisposeStack(Stack S)
{
if (S != NULL)
{
free(S->Array);
free(S);
}
}
void Push(ElementType X, Stack S)
{
if (IsFull(S))
Error("Full stack");
else
S->Array[++S->TopOfStack] = X;
}
ElementType Top(Stack S)
{
if (!IsEmpty(S))
return S->Array[S->TopOfStack];
Error("Empty stack");
return 0; /* Return value used to avoid warning */
}
void Pop(Stack S)
{
if (IsEmpty(S))
Error("Empty stack");
else
S->TopOfStack--;
}
ElementType TopAndPop(Stack S)
{
if (!IsEmpty(S))
return S->Array[S->TopOfStack--];
Error("Empty stack");
return 0; /* Return value used to avoid warning */
}
teststka.c
#include <stdio.h>
#include "stackar.h"
int main()
{
Stack S;
int i;
S = CreateStack(12);
for (i = 0; i < 10; i++)
Push(i, S);
while (!IsEmpty(S))
{
printf("%d\n", Top(S));
Pop(S);
}
DisposeStack(S);
return 0;
}
函数调用关系图(Call graph)