Linux中的哈希表(Hash Table)是一种高效的数据结构,用于存储键值对,并支持快速的查找、插入和删除操作。以下是关于Linux哈希表的基础概念、优势、类型、应用场景以及常见问题及解决方法:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int key;
int value;
struct Node* next;
} Node;
typedef struct HashTable {
int size;
Node** table;
} HashTable;
HashTable* createHashTable(int size) {
HashTable* ht = (HashTable*)malloc(sizeof(HashTable));
ht->size = size;
ht->table = (Node**)malloc(sizeof(Node*) * size);
for (int i = 0; i < size; i++) {
ht->table[i] = NULL;
}
return ht;
}
int hashFunction(int key, int size) {
return key % size;
}
void insert(HashTable* ht, int key, int value) {
int index = hashFunction(key, ht->size);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = key;
newNode->value = value;
newNode->next = NULL;
if (ht->table[index] == NULL) {
ht->table[index] = newNode;
} else {
Node* current = ht->table[index];
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
int search(HashTable* ht, int key) {
int index = hashFunction(key, ht->size);
Node* current = ht->table[index];
while (current != NULL) {
if (current->key == key) {
return current->value;
}
current = current->next;
}
return -1; // Not found
}
void delete(HashTable* ht, int key) {
int index = hashFunction(key, ht->size);
Node* current = ht->table[index];
Node* prev = NULL;
while (current != NULL) {
if (current->key == key) {
if (prev == NULL) {
ht->table[index] = current->next;
} else {
prev->next = current->next;
}
free(current);
return;
}
prev = current;
current = current->next;
}
}
void freeHashTable(HashTable* ht) {
for (int i = 0; i < ht->size; i++) {
Node* current = ht->table[i];
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
}
free(ht->table);
free(ht);
}
int main() {
HashTable* ht = createHashTable(10);
insert(ht, 1, 100);
insert(ht, 11, 200);
printf("Value for key 11: %d\n", search(ht, 11));
delete(ht, 11);
printf("Value for key 11 after deletion: %d\n", search(ht, 11));
freeHashTable(ht);
return 0;
}
通过以上内容,你应该对Linux中的哈希表有了全面的了解,并能够解决常见的相关问题。
领取专属 10元无门槛券
手把手带您无忧上云