Skip to content

Instantly share code, notes, and snippets.

@duclos-cavalcanti
Last active October 7, 2022 04:32
Show Gist options
  • Save duclos-cavalcanti/20745d9805a5b3fdb33aa5c8a949728a to your computer and use it in GitHub Desktop.
Save duclos-cavalcanti/20745d9805a5b3fdb33aa5c8a949728a to your computer and use it in GitHub Desktop.
Simple, generic and opaque data linked list in C
#include "linked_list.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
list_t* new_list() {
list_t* ret = (list_t*) calloc(1, sizeof(list_t));
if (!ret) {
fprintf(stderr, "Creating list failed\n");
exit(EXIT_FAILURE);
}
ret->size = 0;
ret->head = NULL;
return ret;
}
node_t* new_node(void* d, size_t size) {
node_t* ret = (node_t*) calloc(1, sizeof(node_t));
if (!ret) {
fprintf(stderr, "Creating node failed\n");
exit(EXIT_FAILURE);
}
ret->data = calloc(1, sizeof(size));
if (!ret->data) {
fprintf(stderr, "Creating node data failed\n");
exit(EXIT_FAILURE);
}
memcpy(ret->data, d, size);
ret->next = NULL;
ret->key = 0;
return ret;
}
void insert_node(list_t* l, void* d, size_t size, int key) {
node_t* n = new_node(d, size);
n->key = key;
if (is_empty(l)) {
l->head = n;
} else {
node_t* it;
for (it = l->head; it->next; it=it->next){}
it->next = n;
}
++l->size;
}
void step(list_t* l, void (*callback)(node_t* n)) {
node_t* it;
for (it = l->head; it; it=it->next) {
callback(it);
}
}
bool is_empty(list_t* l) {
return (l->head == NULL);
}
void free_list(list_t* l, void (*free_data)(void* d)) {
for (int i = 0; i < l->size; ++i) {
node_t* it;
node_t* prev;
for (it = l->head; it->next; it=it->next) {
prev = it;
}
free_data(it->data);
free(it);
it = NULL;
prev->next = NULL;
}
free(l);
l = NULL;
}
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include <stdbool.h>
#include <stdio.h>
typedef struct node {
int key;
void* data;
struct node* next;
} node_t;
typedef struct list {
unsigned int size;
node_t* head;
} list_t;
list_t* new_list();
void insert_node(list_t* l, void* d, size_t size, int key);
void step(list_t* l, void (*callback)(node_t* n));
bool is_empty(list_t* l);
void free_list(list_t* l, void (*free_data)(void* d));
#endif /* LINKED_LIST_H */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment