哈希算法是一种常用的数据结构,可以用来快速地查找数据。下面是一个用哈希算法和 C 语言实现的 IP 地址查找的例子:
``` #include <stdio.h> #include <stdlib.h> #include <string.h>
#define HASH_SIZE 10 // 哈希表的大小
// 定义 IP 地址结构体 typedef struct { char ip[16]; // IP 地址 char location[32]; // 地理位置 } IP;
// 定义哈希表节点 typedef struct node { IP data; // 存储 IP 地址信息 struct node *next; // 指向下一个节点的指针 } Node;
// 定义哈希表 Node *hash_table[HASH_SIZE];
// 计算哈希值 int hash(char *ip) { int sum = 0; for (int i = 0; i < strlen(ip); i++) { sum += ip[i]; } return sum % HASH_SIZE; }
// 插入 IP 地址 void insert(IP ip) { // 计算哈希值 int h = hash(ip.ip); // 创建新节点 Node new_node = (Node)malloc(sizeof(Node)); new_node->data = ip; new_node->next = NULL; // 将新节点插入哈希表 if (hash_table[h] == NULL) { // 当前哈希桶为空ÿ