#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct name_val name_val; struct name_val { char *name; int value; name_val *next; }; name_val *new_item(const char *name, int value) { name_val *nvp = malloc(sizeof(name_val)); if (!nvp) return NULL; nvp->name = name; nvp->value = value; nvp->next = NULL; return nvp; } name_val *add_front(name_val *list, name_val *item) { item->next = list; return item; } name_val *add_end(name_val *list, name_val *item) { name_val *p; if (!list) return item; for (p = list; p->next; p = p->next) ; p->next = item; return list; } /* sequential search for name in list */ name_val *lookup(name_val *list, const char *name) { for (; list; list = list->next) if (!strcmp(list->name, name)) return list; return NULL; } void print_list(name_val *list) { for (; list; list = list->next) printf("key: %s/t/tvalue: %d/n", list->name, list->value); } int list_length(name_val *list) { int n = 0; for (; list; list = list->next) ++n; return n; } void free_all(name_val *list) { name_val *next; for (; list; list = next) { next = list->next; /* assumes name is freed elsewhere */ free(list); } } name_val *delete_item(name_val *list, const char *name) { name_val *p, *prev = NULL; for (p = list; p; p = p->next) { if (!strcmp(list->name, name)) { if (!prev) list = p->next; else prev->next = p->next; /* assumes name is freed elsewhere */ free(p); return list; } prev = p; } return NULL; /* no match */ } int main() { name_val *list = NULL; list = add_end(list, new_item("I", 0)); list = add_end(list, new_item("love", 1)); list = add_end(list, new_item("you", 2)); print_list(list); } 其它函数未测试,哈哈