/*
Name: stack.c
Copyright: personal
Author: hojor
Date: 07-06-10 10:22
Description: stack
*/
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
#define EmptyTOS (-1)
#define MinStackSize (5)
#define ElementType int
struct StackRecord
{
int Capacity;
int TopOfStack;
ElementType * Array;
};
typedef struct StackRecord * Stack;
//function.list
int IsEmpty(Stack S);
int IsFull(Stack S);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
void Push(ElementType X,Stack S);
void Pop(Stack S);
ElementType Top(Stack S);
ElementType TopAndPop(Stack S);
Stack CreateStack(int MaxElements);
//create stack size of MaxElements
Stack CreateStack( int MaxElements)
{
Stack S;
if(MaxElements < MinStackSize)
printf("Stack size is too small\n");
S = (Stack)malloc(sizeof(struct StackRecord));
if(S == NULL)
printf("Out of space!!\n");
S->Array = (ElementType *)malloc(sizeof(ElementType)*MaxElements);
if(S->Array == NULL)
printf("Out of space!!\n");
S->Capacity = MaxElements;
MakeEmpty(S);
return S;
}
//release Stack routines
void DisposeStack(Stack S)
{
if(S != NULL)
{
free(S->Array);
free(S);
}
}
//Determine whether the stack is empty
int IsEmpty(Stack S)
{
return S->TopOfStack == EmptyTOS;
}
//Determine whether the stack is full
int IsFull(Stack S)
{
return S->TopOfStack == S->Capacity;
}
//create an empty stack routines
void MakeEmpty(Stack S)
{
S->TopOfStack = EmptyTOS;
}
//push stack
void Push(ElementType x,Stack S)
{
if(IsFull(S))
printf("Full stack\n");
else
S->Array[++S->TopOfStack]=x;
}
//return top of stack
ElementType Top(Stack S)
{
if(!IsEmpty(S))
return S->Array[S->TopOfStack];
printf("Empty stack");
return 0;
}
//pop stack
void Pop(Stack S)
{
if(IsEmpty(S))
printf("\nEmpty stack\n");
else
S->TopOfStack--;
}
//gave the top of stack and pop
ElementType TopAndPop(Stack S)
{
if(!IsEmpty(S))
return S->Array[S->TopOfStack--];
printf("\nEmpty stack\n");
return 0;
}
int main(void)
{
int i;
Stack s = CreateStack(10);
for(i=0;i<10;i++)
Push(i,s);
for(i=0;i<10;i++)
printf("%d ",TopAndPop(s));
DisposeStack(s);
system("pause");
return 0;
}