// HIDE_START // vim: ts=4 sw=4 et #include #include #include typedef struct datalist_struct datalist_t; typedef struct item_struct item_t; struct datalist_struct { void *item; datalist_t *next; }; struct item_struct { int key; char *value; }; extern datalist_t *makelist(void); extern void print_item(void *value); extern void search_list(datalist_t *list, int (*compare_func)(void *, void *), void *compare_data, void (*print_value_func)(void *)); extern int compare_key(void *compare_data, void *item_ptr); extern char *copy_string(char *); extern void *checked_malloc(int newsize); extern void *checked_realloc(void *p, int newsize); extern char *getline(void); void print_item(void *value) { item_t *item_ptr; item_ptr = (item_t *) item_ptr; printf("%s\n", item_ptr->value); } int compare_key(void *compare_data, void *item_ptr) { item_t *actual_item_ptr; int search_key; int actual_key; actual_item_ptr = (item_t *) item_ptr; search_key = * (int *) compare_data; actual_key = actual_item_ptr->key; return search_key - actual_key; } // HIDE_END void search_list(datalist_t *list, int (*compare_func)(void *, void *), void *compare_data, void (*print_value_func)(void *)) { datalist_t *p; p = list; while (p != NULL) { if (compare_func(compare_data, p->item) == 0) { print_value_func(p->item); break; } p = p->next; } } // HIDE_START int main(void) { datalist_t *list; int key; if (scanf("%d", &key) != 1) { printf("couldn't read key"); exit(1); } list = makelist(); search_list(list, compare_key, &key, print_item); return 0; } datalist_t *makelist(void) { datalist_t *start, *node_ptr, **prev_slot; item_t *item_ptr; int key; char buf[80]; start = NULL; prev_slot = &start; // Not checking for overflow in buf is a bug. while (scanf("%d %s", &key, buf) == 2) { item_ptr = checked_malloc(sizeof(item_t)); item_ptr->key = key; item_ptr->value = copy_string(buf); node_ptr = checked_malloc(sizeof(datalist_t)); node_ptr->item = (void *) item_ptr; node_ptr->next = NULL; *prev_slot = node_ptr; prev_slot = &node_ptr->next; } return start; } char *copy_string(char *s) { char *new_s; new_s = checked_malloc(strlen(s) + 1); strcpy(new_s, s); return new_s; } void *checked_malloc(int newsize) { void *p; p = malloc(newsize); if (p == NULL) { printf("ran out of memory\n"); exit(1); } return p; } void *checked_realloc(void *p, int newsize) { void *newp; newp = realloc(p, newsize); if (newp == NULL) { printf("ran out of memory\n"); exit(1); } return newp; } char *getline(void) { char *s; int c, size = 10, i = 0; s = checked_malloc(size); while ((c = getchar()) != EOF && c != '\n') { if (i >= size - 1) { size *= 2; s = checked_realloc(s, size); } s[i++] = c; } s[i] = '\0'; return s; } // HIDE_END