3. Stack - Sample Program
3. Stack - Sample Program
/* ---------------------------Constants ------------------------------------*/
#define TRUE 1
#define FALSE 0
#define STACK_EMPTY_VALUE -1
#define SUCCESS 1
#define NO_SUCCESS 0
typedef int boolean;
clrscr();
/* Get the stack size from the user into the global variable – stackSize */
printf("Enter the stack size to keep integers: \n");
scanf("%d", &stackSize);
if (result == SUCCESS)
{
printf("Popped out element is %d.\n", element);
}
else
{
printf("Pop failed, because stack is empty.\n");
int *createStack()
This function creates a stack dynamically that will keep integers:
int *createStack()
{
int *x = NULL;
if (x == NULL)
{
printf("Error in stack memory allocation.\n");
exit(0);
}
boolean isStackFull ()
This function checks if stack is full by checking the value of top. If it has reached to (stackSize-
1) it is full (TRUE), otherwise not (FALSE):
boolean isStackFull()
{
boolean isStackEmpty()
{
if (top == STACK_EMPTY_VALUE)
{
return TRUE;
}
else
{
return FALSE;
}
}
This function pops out an element from stack. If stack is empty then pop has NO_SUCCESS,
otherwise, it returns the value stored at the index top and then decrements the top by 1.
Note that in case of SUCCESS, the popped out element is saved in element that is an
argument whose reference is passed in the function.
void destroyStack():
This function destroys the stack (if it exists) and re-initializes the global variables.
void destroyStack()
{
if (pIntStack != NULL)
{
free(pIntStack);
pIntStack = NULL;
stackSize = 0;
top = -1;
}
}