Skip to content

Instantly share code, notes, and snippets.

@gyakoo
Last active August 29, 2015 14:27
Show Gist options
  • Save gyakoo/9145a5c6b2b98db72bb8 to your computer and use it in GitHub Desktop.
Save gyakoo/9145a5c6b2b98db72bb8 to your computer and use it in GitHub Desktop.
Minimal C stack ADT
typedef struct flt_stack_node
{
void* value;
struct flt_stack_node* prev;
}flt_stack_node;
typedef struct flt_stack
{
struct flt_stack_node* tail;
int n_entries;
}flt_stack;
int flt_stack_create(flt_stack** s)
{
flt_stack* _s = (flt_stack*)flt_calloc(1,sizeof(flt_stack));
if ( !_s ) return 0;
*s = _s;
return 1;
}
void flt_stack_destroy(flt_stack** s)
{
if ( !s || !*s ) return;
flt_stack_clear(*s);
flt_safefree(*s);
}
void flt_stack_clear(flt_stack* s)
{
flt_stack_node *n, *pn;
n=s->tail;
while (n)
{
pn=n->prev;
flt_free(n);
n=pn;
}
s->tail=fltnull;
}
void flt_stack_push(flt_stack* s, void* value)
{
flt_stack_node* sn = (flt_stack_node*)flt_malloc(sizeof(flt_stack_node));
if ( !sn ) return;
++s->n_entries;
sn->value = value;
sn->prev = s->tail;
s->tail = sn;
}
void* flt_stack_top(flt_stack* s)
{
return (s->tail) ? s->tail->value : fltnull;
}
void* flt_stack_pop(flt_stack* s)
{
flt_stack_node* prev=fltnull;
void* v=fltnull;
if ( s->tail )
{
v=s->tail->value;
prev=s->tail->prev;
flt_free(s->tail);
s->tail=prev;
}
return v;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment