1.hashtable的定义
2.hashtable的测试代码
#include <stdio.h>
#include <stdlib.h>
#include "main.h"
#define TABLE_SIZE 10
typedef struct Node {
int key;
int value;
struct Node* next;
} Node;
typedef struct {
Node* head;
} HashTable;
HashTable* createHashTable() {
HashTable* hashtable = (HashTable*)malloc(sizeof(HashTable) * TABLE_SIZE);
for (int i = 0; i < TABLE_SIZE; i++) {
hashtable[i].head = NULL;
}
return hashtable;
}
int hashFunction(int key) {
return key % TABLE_SIZE;
}
void insert(HashTable* hashtable, int key, int value) {
int index = hashFunction(key);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = key;
newNode->value = value;
newNode->next = NULL;
if (hashtable[index].head == NULL) {
hashtable[index].head = newNode;
}
else {
Node* currentNode = hashtable[index].head;
while (currentNode->next != NULL) {
currentNode = currentNode->next;
}
currentNode->next = newNode;
}
}
int search(HashTable* hashtable, int key) {
int index = hashFunction(key);
Node* currentNode = hashtable[index].head;
while (currentNode != NULL) {
if (currentNode->key == key) {
return currentNode->value;
}
currentNode = currentNode->next;
}
return -1; // 返回-1表示未找到对应的值
}
void delete(HashTable* hashtable, int key) {
int index = hashFunction(key);
Node* currentNode = hashtable[index].head;
Node* prevNode = NULL;
while (currentNode != NULL) {
if (currentNode->key == key) {
if (prevNode == NULL) {
hashtable[index].head = currentNode->next;
}
else {
prevNode->next = currentNode->next;
}
free(currentNode);
return;
}
prevNode = currentNode;
currentNode = currentNode->next;
}
}
void display(HashTable* hashtable) {
for (int i = 0; i < TABLE_SIZE; i++) {
printf("Index %d: ", i);
Node* currentNode = hashtable[i].head;
while (currentNode != NULL) {
printf("(%d, %d) ", currentNode->key, currentNode->value);
currentNode = currentNode->next;
}
printf("\n");
}
}
void destroyHashTable(HashTable* hashtable) {
for (int i = 0; i < TABLE_SIZE; i++) {
Node* currentNode = hashtable[i].head;
while (currentNode != NULL) {
Node* tempNode = currentNode;
currentNode = currentNode->next;
free(tempNode);
}
}
free(hashtable);
}
int hash_table_test() {
HashTable* hashtable = createHashTable();
insert(hashtable, 1, 10);
insert(hashtable, 2, 20);
insert(hashtable, 11, 30);
insert(hashtable, 21, 40);
insert(hashtable, 12, 50);
printf("Initial hash table:\n");
display(hashtable);
int keyToSearch = 11;
int searchResult = search(hashtable, keyToSearch);
if (searchResult != -1) {
printf("Value found for key %d: %d\n", keyToSearch, searchResult);
}
else {
printf("Value not found for key %d\n", keyToSearch);
}
int keyToDelete = 2;
delete(hashtable, keyToDelete);
printf("Hash table after deletion of key %d:\n", keyToDelete);
display(hashtable);
destroyHashTable(hashtable);
return 0;
}
3.程序运行结果如下图: