#include #include #include #include "assert.h" struct list_node { int data; struct list_node *next; }; typedef struct list_node list_node_t; int list_length(list_node_t * list) { list_node_t *cur; int count = 0; cur = list; while (cur != NULL) { count++; cur = cur->next; } return count; } bool list_empty(list_node_t *list) { return (list == NULL); } void list_print(list_node_t * list) { list_node_t *cur; cur = list; while (cur != NULL) { printf("%d ", cur->data); cur = cur->next; } printf("\n"); } void list_add(list_node_t *list, list_node_t *item) { list_node_t *cur; cur = list; assert(cur != NULL); while (cur->next != NULL) { cur = cur->next; } cur->next = item; } void list_remove(list_node_t *list, list_node_t *item) { list_node_t *cur; cur = list, assert(cur != NULL); while (cur->next != NULL) { if (cur->next->data == item->data) { cur->next = cur->next->next; return; /* just the first */ } cur = cur->next; } } int main(int argc, char *argv[]) { list_node_t *emptylist = NULL; assert(list_length(emptylist) == 0); assert(list_empty(emptylist) == true); list_print(emptylist); printf("list_length = %d\n", list_length(emptylist)); list_node_t foo = { 1, NULL }; assert(list_length(&foo) == 1); assert(list_empty(&foo) == false); list_print(&foo); printf("list_length = %d\n", list_length(&foo)); // append something to foo list_node_t bar = { 2, NULL }; list_add(&foo, &bar); assert(list_length(&foo) == 2); assert(list_length(&bar) == 1); list_print(&foo); printf("list_length = %d\n", list_length(&foo)); // append more const int howmany = 100; for(int i = 0; i < howmany; i++) { list_node_t *newnode = malloc(sizeof(list_node_t)); newnode->data = i; list_add(&foo, newnode); } assert(list_length(&foo) == 2 + howmany); list_print(&foo); printf("list_length = %d\n", list_length(&foo)); // remove something list_node_t toremove = { 23, NULL }; list_remove(&foo, &toremove); assert(list_length(&foo) == 2 + howmany - 1); list_print(&foo); printf("list_length = %d\n", list_length(&foo)); // remove something toremove.data = 99; list_remove(&foo, &toremove); assert(list_length(&foo) == 2 + howmany - 2); list_print(&foo); printf("list_length = %d\n", list_length(&foo)); // remove something toremove.data = 1; list_remove(&foo, &toremove); /* FIXME can't delete first 1 */ assert(list_length(&foo) == 2 + howmany - 3); list_print(&foo); printf("list_length = %d\n", list_length(&foo)); }