链表解决哈希碰撞就是在发生哈希碰撞时,在现有的地址再串联一个新的链表存储数据。
下面是简单的示例代码:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
/***********************************************************/
// 程序名称:HashSearch_2.cpp // 程序目的:设计一个哈希查找的程序,运用余数法做为哈希函数,链表 // 法解决哈希冲突,设计哈希表 // 程序来源:数据结构与算法分析(C语言版) P-311 // 日期: 2013-8-31 11:07:43 JohnnyHu改进 /***********************************************************/ #include <stdio.h> #include <stdlib.h> #define MAX 6 #define HASHMAX 5 #define NotFound - 1 typedef int ElementType; int data[MAX] = { 1, 13, 20, 5, 12, 33}; typedef struct node { ElementType key; // 键值 struct node* next; // 下一个节点 } Node; typedef Node listNode; typedef Node* link; Node hashTab[HASHMAX]; // 哈希表 int counter = 0; // 计数器 int HashMod(ElementType key); void CreateHashTable(ElementType key); int HashSearch(ElementType key); int main( void) { printf( "输出原有数据:\n"); for ( int i= 0; i < MAX; i++) printf( "[%d] ", data[i]); printf( "\n\n"); int index = 0; while (index < MAX) // 创建哈希表 { CreateHashTable(data[index]); index++; } link pointer; for ( int i = 0; i < HASHMAX; i++) { printf( "HashTab[%d]: ", i); pointer = hashTab[i].next; while ( NULL != pointer) { if (pointer->key > 0) printf( "[%d]", pointer->key); pointer = pointer->next; } printf( "\n"); } ElementType keyValue = 0; while ( - 1 != keyValue) { printf( "请输入要查询的值(int值)(-1退出):"); scanf( "%d", &keyValue); if (NotFound != HashSearch(keyValue)) printf( "查询次数:%d\n", counter); // 查询次数 else printf( "没找到!"); } return 0; } // 哈希函数余数法 int HashMod(ElementType key) { return key % HASHMAX; } // 创建哈希表 void CreateHashTable(ElementType key) { link pointer; // 列表指针 link pNew; // 新列表指针 int index; // 哈希索引 pNew = (link)malloc( sizeof(Node)); // 内存配置 pNew->key = key; // 键值 pNew->next = NULL; // 指向指针结束 index = HashMod(key); // 数据位置 pointer = hashTab[index].next; if ( NULL != pointer) { pNew->next = pointer; // 指向上一个指针 hashTab[index].next = pNew; // 哈希表指向新指针 } else hashTab[index].next = pNew; // 哈希表指向新指针 } // 哈希查找 int HashSearch(ElementType key) { link pointer; // 列表指针 int index; // 哈希索引 counter = 0; // 全局函数 index = HashMod(key); // 取得数据位置 pointer = hashTab[index].next; // 哈希表起始指针 printf( "data[%d]: ", index); while ( NULL != pointer) { counter++; if (pointer->key == key) // 找到数据 return 1; else pointer = pointer->next; // 下一个指针 } return NotFound; } |