/* ** $Id: lists.c 789 2008-02-23 06:27:49Z phf $ ** ** Linked list code from Spring 2008. Sorry, very few ** comments, please ask if you don't get something. */ #include #include struct node { struct node *next; int data; }; struct node *head = NULL; void insert(int x) { struct node *node = malloc(sizeof(struct node)); node->next = head; node->data = x; head = node; } struct node *find(int x, struct node **prev) // horrible :-) { struct node *node = head; struct node *nprv = NULL; while (node != NULL && node->data != x) { nprv = node; node = node->next; } *prev = nprv; // fake 2nd result return node; } void rem(int x) { struct node *prev; struct node *node = find(x, &prev); if (node != NULL) { if (prev != NULL) { prev->next = node->next; } else { // prev == NULL head = node->next; } free(node); } } void print(void) { for (struct node *node = head; node != NULL; node = node->next) { printf("node at %p has data %d\n", node, node->data); } puts("--------"); } int main() { print(); // head: --| // insert 7 insert(7); print(); // head: -->[7]--| // insert 12 insert(12); print(); // head: -->[12]-->[7]--| insert(1); print(); insert(36); print(); // head: -->[36]-->[1]-->[12]-->[7]--| rem(4); print(); rem(1); print(); rem(36); print(); rem(7); print(); rem(12); print(); return EXIT_SUCCESS; }