#include <stdlib.h>
#include <stdio.h>
#include <string.h>
// 栈操作数组实现
typedef int ElementType;
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);
void _Test(void);
#define EmptyTOS (-1)
#define MinStackSize (5)
#define Error(str) fprintf(stderr,"%s/n", str),exit(1)
struct StackRecord {
int Capacity;
int TopOfStack;
ElementType *Array;
};
// 判断栈是否为空
int IsEmpty(Stack S)
{
return S->TopOfStack == EmptyTOS;
}
// 判断栈是否已满
int IsFull(Stack S)
{
return S-> Capacity == S->TopOfStack;
}
Stack CreateStack(int MaxElements)
{
Stack S;
if(MaxElements < MinStackSize){
Error("Stack size too small");
}
S = malloc(sizeof(struct StackRecord));
if(S == NULL){
Error("Out of space!!!");
}
S->Array = malloc(sizeof(ElementType) * MaxElements);
if(S->Array == NULL){
Error("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;
}
void Pop(Stack S)
{
if(IsEmpty(S)){
Error("Empty Stack");
}else{
S->TopOfStack--;
}
}
ElementType TopAndPop(Stack S)
{
if(IsEmpty(S)){
Error("Empty stack");
return 0;
}else{
return S->TopOfStack--;
}
}
void _Test(void)
{
int a, b, c;
Stack S;
a = 1;
b = 2;
c = 3;
S = CreateStack(10);
if(S == NULL){
Error("create stack err");
}
Push(a, S);
printf("%d\\n", Top(S));
Push(b, S);
printf("%d\\n", Top(S));
Pop(S);
printf("%d\\n", Top(S));
MakeEmpty(S);
Push(c, S);
printf("%d\\n", Top(S));
}