您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在计算机科学中,哈希表(Hash Table)是一种通过哈希函数将键映射到值的数据结构。它提供了快速的插入、删除和查找操作。指针可以在实现哈希表时发挥重要作用,特别是在处理动态内存分配和链式哈希(Separate Chaining)时。
以下是使用指针实现哈希表的基本步骤:
定义哈希表的结构:
定义链表节点的结构:
初始化哈希表:
NULL
。哈希函数:
插入操作:
查找操作:
删除操作:
以下是一个简单的C语言示例,展示了如何使用指针实现一个基本的哈希表:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 10
// 定义链表节点结构
typedef struct Node {
char *key;
int value;
struct Node *next;
} Node;
// 定义哈希表结构
typedef struct HashTable {
Node **table;
} HashTable;
// 哈希函数
unsigned int hash(const char *key) {
unsigned int hash = 0;
while (*key) {
hash = (hash * 31) + *key++;
}
return hash % TABLE_SIZE;
}
// 初始化哈希表
HashTable *create_table() {
HashTable *ht = (HashTable *)malloc(sizeof(HashTable));
ht->table = (Node **)malloc(sizeof(Node *) * TABLE_SIZE);
for (int i = 0; i < TABLE_SIZE; i++) {
ht->table[i] = NULL;
}
return ht;
}
// 插入操作
void insert(HashTable *ht, const char *key, int value) {
unsigned int index = hash(key);
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->key = strdup(key);
new_node->value = value;
new_node->next = ht->table[index];
ht->table[index] = new_node;
}
// 查找操作
int lookup(HashTable *ht, const char *key) {
unsigned int index = hash(key);
Node *current = ht->table[index];
while (current != NULL) {
if (strcmp(current->key, key) == 0) {
return current->value;
}
current = current->next;
}
return -1; // 未找到
}
// 删除操作
void delete(HashTable *ht, const char *key) {
unsigned int index = hash(key);
Node *current = ht->table[index];
Node *prev = NULL;
while (current != NULL) {
if (strcmp(current->key, key) == 0) {
if (prev == NULL) {
ht->table[index] = current->next;
} else {
prev->next = current->next;
}
free(current->key);
free(current);
return;
}
prev = current;
current = current->next;
}
}
// 释放哈希表内存
void free_table(HashTable *ht) {
for (int i = 0; i < TABLE_SIZE; i++) {
Node *current = ht->table[i];
while (current != NULL) {
Node *temp = current;
current = current->next;
free(temp->key);
free(temp);
}
}
free(ht->table);
free(ht);
}
int main() {
HashTable *ht = create_table();
insert(ht, "apple", 10);
insert(ht, "banana", 20);
printf("apple: %d\n", lookup(ht, "apple"));
printf("banana: %d\n", lookup(ht, "banana"));
delete(ht, "apple");
printf("apple after delete: %d\n", lookup(ht, "apple"));
free_table(ht);
return 0;
}
这个示例展示了如何使用指针和链表来实现一个简单的哈希表。实际应用中可能需要更多的功能和优化,例如动态调整哈希表大小、更好的哈希函数等。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。