I give you an example of stack implementation (together with an example of its usage):
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
struct stack
{
char data;
struct stack * down;
};
struct stack * push(struct stack * top, char data)
{
struct stack * newtop = (struct stack *) malloc( sizeof (struct stack) );
assert(newtop);
newtop->data = data;
newtop->down = top;
return newtop;
}
struct stack * pop( struct stack * top)
{
if ( ! top ) return NULL;
struct stack * newtop = top->down;
free( top);
return newtop;
}
int main()
const char * s = "Hello World!";
struct stack * top = NULL;
while ( *s )
{
top = push( top, *s);
++s;
}
while (top)
{
putchar(top->data);
top = pop(top);
}
putchar('\n');
return 0;
}
Please note, the memory allocation strategy used is not efficient. For instace with deep stacks, the ready-made
C++ stack class[
^] (leveraging the memory allocation strategy of
STL
containers) is way faster.