Stack.h
#ifndef _STACK_H
typedef struct Stack * PtrStack;
void MakeEmpty(PtrStack S);
PtrStack CreateStack(int size);
bool IsFull(PtrStack S);
bool IsEmpty(PtrStack S);
void DeleteStack(PtrStack S);
void Push(int X, PtrStack S);
int Pop(PtrStack S);
int Top(PtrStack S);
#endif
struct Stack
{
int capacityOfStack;
int topOfStack;
int * arrayOfStack;
};
Stack.cpp
#include "StdAfx.h"
#include "Stack.h"
#define EmptyTop (-1)
PtrStack CreateStack(int size)
{
PtrStack S = NULL;
S = new Stack();
if (S == NULL)
throw "Fail to new a stack!";
S->arrayOfStack = new int[size]();
if (S->arrayOfStack == NULL)
throw "Fail to new array of stack!";
S->capacityOfStack = size;
MakeEmpty(S);
return S;
}
void MakeEmpty(PtrStack S)
{
S->topOfStack = EmptyTop;
}
bool IsFull(PtrStack S)
{
if (S->topOfStack == S->capacityOfStack - 1)
return true;
else
return false;
}
bool IsEmpty(PtrStack S)
{
if (S->topOfStack == EmptyTop)
return true;
else
return false;
}
void DeleteStack(PtrStack S)
{
if (S)
{
delete[] S->arrayOfStack;
delete S;
S = NULL;
}
}
void Push(int X, PtrStack S)
{
if (IsFull(S))
throw "The stack if full!";
else
{
S->topOfStack++;
S->arrayOfStack[S->topOfStack] = X;
}
}
int Pop(PtrStack S)
{
if (IsEmpty(S))
throw "Empty stack!";
else
return S->arrayOfStack[S->topOfStack--];
}
int Top(PtrStack S)
{
if (IsEmpty(S))
throw "Empty stack!";
else
return S->arrayOfStack[S->topOfStack];
}