(C语言版数据结构)实现哈希表的构造和查找算法,要求:用除留余数法构造哈希表,用链地址法解决冲突
时间: 2024-05-11 07:10:20 浏览: 26
以下是C语言版数据结构实现哈希表的构造和查找算法,使用除留余数法构造哈希表,用链地址法解决冲突:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 13 //哈希表长度
//定义哈希表节点
typedef struct HashNode {
int key;
struct HashNode *next;
} HashNode;
//定义哈希表
typedef struct HashTable {
HashNode *head[MAXSIZE];
} HashTable;
//哈希函数
int HashFunction(int key) {
return key % MAXSIZE;
}
//初始化哈希表
void HashInit(HashTable *hashTable) {
for (int i = 0; i < MAXSIZE; i++) {
hashTable->head[i] = NULL;
}
}
//插入节点
void HashInsert(HashTable *hashTable, int key) {
int index = HashFunction(key);
HashNode *node = (HashNode *)malloc(sizeof(HashNode));
node->key = key;
node->next = NULL;
if (hashTable->head[index] == NULL) {
hashTable->head[index] = node;
} else {
HashNode *p = hashTable->head[index];
while (p->next != NULL) {
p = p->next;
}
p->next = node;
}
}
//查找节点
HashNode *HashSearch(HashTable *hashTable, int key) {
int index = HashFunction(key);
HashNode *p = hashTable->head[index];
while (p != NULL && p->key != key) {
p = p->next;
}
return p;
}
//打印哈希表
void PrintHashTable(HashTable *hashTable) {
for (int i = 0; i < MAXSIZE; i++) {
printf("hashTable[%d]: ", i);
HashNode *p = hashTable->head[i];
while (p != NULL) {
printf("%d ", p->key);
p = p->next;
}
printf("\n");
}
}
int main() {
HashTable hashTable;
HashInit(&hashTable);
int keys[] = {12, 3, 23, 14, 7, 8, 9, 10, 11, 5, 6, 16, 21};
int n = sizeof(keys) / sizeof(keys[0]);
for (int i = 0; i < n; i++) {
HashInsert(&hashTable, keys[i]);
}
PrintHashTable(&hashTable);
int key = 7;
HashNode *node = HashSearch(&hashTable, key);
if (node != NULL) {
printf("Find key %d\n", key);
} else {
printf("Not find key %d\n", key);
}
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)