A simple implementation of a stack – C language
A stack is a last in, first out (LIFO) abstract data type and linear data structure.
It is characterized by two fundamental operations, called push and pop. The push operation adds a new item to the top of the stack, while the pop operation removes an item from the top of the stack.
The stack data type can be used in several applications:
- Towers of Hanoi
- Expression evaluation and syntax parsing
- Rearranging railroad cars
- Backtracking
- Quicksort
- Runtime memory management
and many more
Now let's write few lines of code:
First of all the data structure:
typedef struct i_stack_s
{
int data;
struct i_stack_s *link;
}i_stack_t;
then we are going to write the prototypes:
void pushItem(i_stack_t **aStack, int aData);
int popItem(i_stack_t **aStack);
int isEmpty(i_stack_t *aStack);
The isEmpty function will check if the stack is empty:
int isEmpty(i_stack_t *aStack)
{
if(aStack==NULL)
{
return(1);
}
else
{
return(0);
}
}
the popItem will extract the last inserted item
int popItem(i_stack_t **aStack)
{
if(isEmpty(*aStack))
{
fprintf(stderr, "Error: i_stack underflow\n");
abort();
}
else
{
i_stack_t *top = *aStack;
int value = top->data;
*aStack = top->link;
free(top);
return value;
}
}
the pushItem will add a new item at the beginning of the srtucture:
void pushItem(i_stack_t **aStack, int aData)
{
/* create a new node */
i_stack_t *node = malloc(sizeof(i_stack_t));
if (node == NULL)
{
perror("Error: no space available for node\n");
exit(EXIT_FAILURE);
}
else
{
/* initialize node */
node->data = aData;
if(isEmpty(*aStack))
{
node->link = NULL;
}
else
{
node->link = *aStack;
}
*aStack = node;
}
}
Last we are going to write a simple test program, it will push into the stack 10 items and then it will pop 10 items and print back the results:
int main(void)
{
int i;
i_stack_t *myStack;
for(i=0; i<10; i++)
{
pushItem(&myStack, i);
}
for(i=0; i<10; i++)
{
printf("Element number %d --> value %d\n", i, popItem(&myStack));
}
exit(EXIT_SUCCESS);
}
Gg1

