标签:
#include <stdio.h> #include <stdlib.h> /*通过链接法解决碰撞*/ typedef struct list_node_tag { int key; struct list_node_tag *prev; struct list_node_tag *next; } list_node; typedef struct hash_tag { list_node **list_array; int num; } hash; void list_node_ini(list_node *p, int key){ p->key = key; p->prev = NULL; p->next = NULL; } list_node *list_search(list_node *x, int k){ while (x != NULL && x->key != k) { x = x->next; } return x; } void list_insert(list_node **head, list_node *x){ x->next = *head; if (*head != NULL) { (*head)->prev = x; } *head = x; x->prev = NULL; } void list_delete(list_node **head, list_node *x){ if (x->prev != NULL) { x->prev->next = x->next; } else { *head = x->next; } if (x->next != NULL) { x->next->prev = x->prev; } free(x); } hash *hash_create(int num){ hash *h = (hash*)malloc(sizeof(hash)); h->num = num; h->list_array = (list_node**)calloc(sizeof(list_node*), num); for (int i = 0; i < num; i++) { h->list_array[i] = NULL; } return h; } void hash_destroy(hash *h){ for (int i = 0; i < h->num; i++) { for(list_node * p = h->list_array[i]; p != NULL; ){ list_node * q = p; p = p -> next; free(q); } }; free(h->list_array); free(h); } int hash_value(hash *h, int key){ return key % h->num; } void hash_insert(hash *h, int key){ list_node *x = (list_node*)malloc(sizeof(list_node)); x->key = key; x->prev = NULL; x->next = NULL; list_node **head = &h->list_array[hash_value(h, key)]; list_insert(head, x); } list_node *hash_search(hash *h, int key){ list_node *head = h->list_array[hash_value(h, key)]; return list_search(head, key); } void hash_delete(hash *h, list_node *x){ if (x == NULL) return; int key = x->key; list_node **head = &h->list_array[hash_value(h, key)]; list_delete(head, x); } int main(){ hash *h = hash_create(10); for (int i = 0; i < 10; i++) { printf("%d ", i); hash_insert(h, i); } printf("\n"); int k = 0; list_node *x = hash_search(h, k); printf("查找关键字:%d的结果:%s\n", k, x != NULL ? "成功" : "失败"); if (x != NULL) { hash_delete(h, x); x = hash_search(h, k); printf("删除关键字:%d的结果:%s\n", k, x == NULL ? "成功" : "失败"); } hash_destroy(h); return 0; }
标签:
原文地址:http://www.cnblogs.com/moxiaopeng/p/4948445.html