栈的数组实现
#include <stdio.h>
#include <stdlib.h>
struct StackRecord;
typedef struct StackRecord *Stack;
int IsEmpty(Stack S);
int IsFull(Stack S);
Stack CreateStack(int MaxElement);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
void Push(int X,Stack S);
void Pop(Stack S);
void Top(Stack S);
#define EmptyTOS (-1)
#define MinStackSize (5)
struct StackRecord
{
int Capacity;
int TopOfStack;
int * Array;
};
void main()
{
Stack s;
s=CreateStack(5);
Push(4,s);
Top(s);
}
Stack
CreateStack(int MaxElement)
{
Stack S;
if(MaxElement<MinStackSize)
printf("Stack is too small.");
else
S->Array=(struct StackRecord *)malloc(sizeof(Stack)*MaxElement);
if(S->Array==NULL)
printf("Out of space.");
S->Capacity=MaxElement;
MakeEmpty(S);
return S;
}
void
DisposeStack(Stack S)
{
if(S!=NULL)
{
free(S->Array);
free(S);
}
}
int
IsEmpty(Stack S)
{
return S->TopOfStack==EmptyTOS;
}
void
Push(int X,Stack S)
{
if(IsFull(S))
printf("Full Stack.");
else
S->Array[++S->TopOfStack]=X;
}
void
Pop(Stack S)
{
if(IsEmpty(S))
printf("Empty Stack.");
else
S->TopOfStack--;
}
void
Top(Stack S)
{
if(!IsEmpty(S))
printf("%d",S->Array[S->TopOfStack]);
else
printf("Empty Stack.");
}