Skip to content

Instantly share code, notes, and snippets.

@pseudomuto
Last active November 17, 2019 10:52
Show Gist options
  • Save pseudomuto/6334735 to your computer and use it in GitHub Desktop.
Save pseudomuto/6334735 to your computer and use it in GitHub Desktop.
Blog Code: Implementing a Generic Stack in C
#include <stdlib.h>
#include <assert.h>
#include "stack.h"
void stack_new(stack *s, int elementSize, freeFunction freeFn)
{
s->list = malloc(sizeof(list));
// make sure the malloc call didn't fail...
assert(s->list != NULL);
list_new(s->list, elementSize, freeFn);
}
void stack_destroy(stack *s)
{
list_destroy(s->list);
free(s->list);
}
void stack_push(stack *s, void *element)
{
list_prepend(s->list, element);
}
void stack_pop(stack *s, void *element)
{
// don't pop an empty stack!
assert(stack_size(s) > 0);
list_head(s->list, element, TRUE);
}
void stack_peek(stack *s, void *element)
{
assert(stack_size(s) > 0);
list_head(s->list, element, FALSE);
}
int stack_size(stack *s)
{
return list_size(s->list);
}
#ifndef __STACK_H
#define __STACK_H
// from previous post on linked-list implementation
// in C
#include "list.h"
typedef struct {
list *list;
} stack;
void stack_new(stack *s, int elementSize, freeFunction freeFn);
void stack_destroy(stack *s);
void stack_push(stack *s, void *element);
void stack_pop(stack *s, void *element);
void stack_peek(stack *s, void *element);
int stack_size(stack *s);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment