my_stack_in_array.h
#ifndef MY_STACK_IN_ARRAY
#define MY_STACK_IN_ARRAY
#define elementType int
struct my_stack_in_array
{
int capacity;
int topOfStack;
elementType *Array;
};
typedef struct my_stack_in_array myStack;
typedef struct my_stack_in_array * Stack;
typedef Stack Node;
void fatalError(const char * );
int isEmpty(Stack stack);
int isFull(Stack stack);
Stack createStack(int capacity);
void disposeStack(Stack stack);
void makeEmpty(Stack stack);
void push(Stack stack, elementType X);
void pop(Stack stack);
elementType top(Stack stack);
elementType topAndpop(Stack);
#define emptyTOS (-1)
#define minStackSize (5)
#endif
my_stack_in_array.c
#include "my_stack_in_array.h"
#include <stdio.h>
#include <stdlib.h>
void fatelError(const char * outprint)
{
printf(outprint);
fflush(stdout);
exit(EXIT_FAILURE);
}
int isEmpty(Stack stack)
{
return stack->topOfStack == emptyTOS;
}
int isFull(Stack stack)
{
return stack->capacity == stack->topOfStack;
}
Stack createStack(int capacity)
{
Stack stack = (Stack)malloc(sizeof(Stack));
if(stack == NULL)
fatelError("can not malloc stack!\n");
stack->capacity = capacity;
stack->topOfStack = emptyTOS;
stack->Array = (elementType *)malloc(sizeof(elementType)*stack->capacity);
return stack;
}
void disposeStack(Stack stack)
{
free(stack);
}
void makeEmpty(Stack stack)
{
stack->topOfStack = emptyTOS;
}
void push(Stack stack, elementType X)
{
if (isFull(stack))
fatelError("stack is full \n");
else
stack->Array[++(stack->topOfStack)] = X;
}
void pop(Stack stack)
{
if(isEmpty(stack))
fatelError("stack is empty \n");
else
stack->topOfStack--;
}
elementType top(Stack stack)
{
if(isEmpty(stack))
{
fatelError("stack is empty \n");
return -1;
}
else
return stack->Array[stack->topOfStack];
}
elementType topAndpop(Stack stack)
{
if(isEmpty(stack))
{
fatelError("stack is empty \n");
return -1;
}
return stack->Array[stack->topOfStack--];
}
my_stack_in_array_test.c
#include "my_stack_in_array.c"
#define theStackSize 20
int main()
{
Stack stack = createStack(theStackSize);
for(int i = 0; i < theStackSize; i++)
push(stack, i*9);
for(int i = 0; i < theStackSize+5; i++)
printf("%d \n", topAndpop(stack));
}