#include #include #include #include typedef struct node { void *content; struct node *next; }Node; typedef struct slist { Node *head; size_t w; }SList; SList *new_slist(size_t w) { SList *l = malloc(sizeof(SList)); l->head = NULL; l->w = w; return l; } bool is_empty(SList *l) { return !l->head; } void delete_head(SList *l) { Node *n = l->head; //free(n->content); l->head = n->next; free(n); } void destroy_node(Node *n, Node *prev) { //free(n->content); prev->next = n->next; free(n); } void destroy_list(SList *l) { while (!is_empty(l)) delete_head(l); free(l); } void delete_node(Node *n, SList *l) { Node *prev = l->head; while (prev && prev->next != n) prev = prev->next; if (prev) destroy_node(n, prev); } void delete_index(SList *l, int index) { Node *prev, *n = l->head; for (int i = 0; n && i < index; i++) { prev = n; n = n->next; } destroy_node(n, prev); } int get_len(SList *l) { if (is_empty(l)) return 0; int i = 1; Node *n = l->head; do { n = n->next; i++; }while(n); return i-1; } void insert_after(void *content, SList *l, Node *prev) { Node *n = malloc(sizeof(Node)); n->content = content; n->next = prev->next; prev->next = n; } void insert_head(void *content, SList *l) { Node *n = malloc(sizeof(Node)); n->content = content; n->next = l->head; l->head = n; } void insert_empty(void *content, SList *l) { insert_head(content, l); } void insert(void *content, SList *l, int pos) { if (is_empty(l) || !pos) { insert_head(content, l); return; } Node *prev = l->head; while(pos > 1 && prev) { prev = prev->next; pos--; } insert_after(content, l, prev); } void append(void *content, SList *l) { if (is_empty(l)) { insert_empty(content, l); return; } Node *prev = l->head; while(prev->next) prev = prev->next; insert_after(content, l, prev); } Node *find(void *content, SList *l, int (*cmp)(void *a, void *b)) { Node *n = l->head; while (cmp(n->content, content)) { n = n->next; if (!n) return NULL; } return n; } void print_list(SList *l, void (*print_content)(void *content)) { Node *n = l->head; printf("["); while(n) { print_content(n->content); printf(", "); n = n->next; } printf("]\n"); } void print_content(void *c) { printf("%d", *((int *)c)); } int cmp(void *a, void *b) { return *(int *)a - *(int *)b; } int main() { SList *l = new_slist(sizeof(int)); int *a=malloc(sizeof(int)), *b=malloc(sizeof(int)), *c=malloc(sizeof(int)), *d=malloc(sizeof(int)); *a = 1; *b = 2; *c = 3; *d = 4; append(a, l); delete_head(l); insert(a, l, 0); append(b, l); insert(c, l, 1); insert(d, l, 0); append(a, l); printf("%d\n", get_len(l)); destroy_list(l); free(a); free(b); free(c); free(d); }