-
-
Save kostyll/60d699a44b2735aa49380db16910c8cc to your computer and use it in GitHub Desktop.
Blog Code: Implementing a Generic Stack in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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