赞
踩
#include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 10 typedef struct hash_table_item_s { int key; int value; struct hash_table_item_s* next; } hash_table_item; hash_table_item* hash_table[SIZE]; int hash_function(int key) { return key % SIZE; } void hash_table_insert(int key, int value) { int index = hash_function(key); hash_table_item* item = malloc(sizeof(hash_table_item)); item->key = key; item->value = value; item->next = hash_table[index]; hash_table[index] = item; } hash_table_item* hash_table_search(int key) { int index = hash_function(key); hash_table_item* item = hash_table[index]; while (item) { if (item->key == key) { return item; } item = item->next; } return NULL; } void hash_table_delete(int key) { int index = hash_function(key); hash_table_item* item = hash_table[index]; hash_table_item* prev = NULL; while (item) { if (item->key == key) { if (prev) { prev->next = item->next; } else { hash_table[index] = item->next; } free(item); return; } prev = item; item = item->next; } } int main() { hash_table_insert(1, 10); hash_table_insert(2, 20); hash_table_insert(3, 30); hash_table_item* item = hash_table_search(2); if (item) { printf("key: %d, value: %d\n", item->key, item->value); } hash_table_delete(2); item = hash_table_search(2); if (item) { printf("key: %d, value: %d\n", item->key, item->value); } else { printf("key not found\n"); } return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。