Skip to content

Instantly share code, notes, and snippets.

@Keyaku
Last active July 18, 2021 16:09
Show Gist options
  • Save Keyaku/b02268cc3d0f0fa5907d2ebac49ac13f to your computer and use it in GitHub Desktop.
Save Keyaku/b02268cc3d0f0fa5907d2ebac49ac13f to your computer and use it in GitHub Desktop.
A simple but effective Stack structure in C for School projects.
#include <stdlib.h>
#include <string.h>
#include "stack.h"
Stack *stack_new(Stack *st, size_t size, bool (*equals)(const void*, const void*))
{
if (size <= 0) return NULL;
st->idx = 0;
st->max = size;
st->data = salloc(size, sizeof(*st->data), false);
st->equals = equals;
return st;
}
size_t stack_size(Stack *st)
{
return st != NULL ? st->idx : 0;
}
bool stack_is_empty(Stack *st) { return st->idx == 0; }
bool stack_contains(Stack *st, Object key)
{
if (st->equals == NULL) {
fprintf(stderr, "%s: equals callback undefined\n", __func__);
return false;
}
for (int idx = 0; idx < stack_size(st); idx++) {
if (st->equals(st->data[idx], key)) {
return true;
}
}
return false;
}
void stack_push(Stack *st, Object key)
{
if (st == NULL) { return; }
if (st->idx == st->max) { return; }
if (stack_contains(st, key)) { return; }
st->data[++st->idx] = key;
}
Object stack_pop(Stack *st)
{
if (st == NULL) { return NULL; }
return st->data[st->idx--];
}
void stack_reset(Stack *st)
{
st->idx = 0;
}
void stack_destroy(Stack *st)
{
if (st == NULL) { return; }
free(st->data); st->data = NULL;
st->idx = st->max = 0;
}
#ifndef _STACK_H_
#define _STACK_H_
typedef unsigned char bool;
#define true 1
#define false 0
typedef void* Object;
typedef struct _stack {
size_t idx, max;
Object *data; /* data[idx] = void* */
bool (*equals)(const void*, const void*);
} Stack;
Stack *stack_new(Stack *st, size_t size, bool (*equals)(const void*, const void*));
size_t stack_size(Stack *st);
bool stack_is_empty(Stack *st);
bool stack_contains(Stack *st, Object key);
void stack_push(Stack *st, Object key);
Object stack_pop(Stack *st);
void stack_reset(Stack *st);
void stack_destroy(Stack *st);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment