Skip to content

Instantly share code, notes, and snippets.

@sophiawisdom
Last active June 20, 2022 01:41
Show Gist options
  • Select an option

  • Save sophiawisdom/e6fb7a9795162f3969e24811a51c609e to your computer and use it in GitHub Desktop.

Select an option

Save sophiawisdom/e6fb7a9795162f3969e24811a51c609e to your computer and use it in GitHub Desktop.
// I'm assuming these are 8 bytes for the moment because C doesn't have generic functions.
struct list {
int capacity;
int start_i;
int end_i;
}
struct list *allocate(int size) {
int list_size = size * sizeof(void *);
struct list *stuff = malloc(list_size + sizeof(struct list));
stuff -> capacity = size;
return stuff;
}
void *pop_beginning(struct list *l) {
void *first_item = l+sizeof(struct list)+ (sizeof(void *) * l -> start_i);
l -> start_i++;
return first_item;
}
void *pop_end(struct list *l) {
// assume they're not popping too far
void *last_item = l+sizeof(struct list) + (sizeof(void *) * l -> start_i);
l -> end_i--;
return last_item;
}
int push_beginning(struct list *l, void *object) {
if (l -> start_i == 0) {
// reallocate the list from the beginning
}
*(l + sizeof(struct list) + (l -> start_i-- * sizeof(void *))) = object;
return 1;
}
int push_end(struct list *l, void *object) {
if (l -> end_i == capacity) {
// realloc
}
*(l + sizeof(struct list) + (l -> end_i++ * sizeof(void *))) = object;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment