引言C语言作为一种历史悠久且广泛使用的编程语言,在构建高效数据结构方面具有强大的能力。字典(或称为哈希表)作为一种重要的数据结构,在许多编程场景中扮演着关键角色。本文将揭秘C语言字典源码,从零开始构建...
C语言作为一种历史悠久且广泛使用的编程语言,在构建高效数据结构方面具有强大的能力。字典(或称为哈希表)作为一种重要的数据结构,在许多编程场景中扮演着关键角色。本文将揭秘C语言字典源码,从零开始构建一个高效的数据结构。
字典是一种存储键值对的数据结构,它通过哈希函数将键映射到数组中的一个位置,从而实现快速检索。以下是构建字典的基本步骤:
以下是一个简单的C语言字典源码实现,使用链地址法解决哈希冲突:
#include
#include
#define TABLE_SIZE 1013 // 使用质数作为哈希表大小
typedef struct Node { int key; int value; struct Node *next;
} Node;
Node* hashTable[TABLE_SIZE];
// 哈希函数
unsigned int hash(int key) { return key % TABLE_SIZE;
}
// 初始化哈希表
void initHashTable() { for (int i = 0; i < TABLE_SIZE; i++) { hashTable[i] = NULL; }
}
// 插入键值对
void insert(int key, int value) { unsigned int index = hash(key); Node *newNode = (Node*)malloc(sizeof(Node)); newNode->key = key; newNode->value = value; newNode->next = hashTable[index]; hashTable[index] = newNode;
}
// 查找键值对
int find(int key) { unsigned int index = hash(key); Node *node = hashTable[index]; while (node != NULL) { if (node->key == key) { return node->value; } node = node->next; } return -1; // 未找到
}
// 删除键值对
void remove(int key) { unsigned int index = hash(key); Node *node = hashTable[index]; Node *prev = NULL; while (node != NULL) { if (node->key == key) { if (prev == NULL) { hashTable[index] = node->next; } else { prev->next = node->next; } free(node); return; } prev = node; node = node->next; }
}
int main() { initHashTable(); insert(1, 10); insert(2, 20); insert(3, 30); printf("Find key 2: %d\n", find(2)); remove(2); printf("Find key 2 after removal: %d\n", find(2)); return 0;
} 通过以上C语言字典源码实现,我们可以看到构建高效数据结构的基本步骤。在实际应用中,可以根据具体需求对字典进行扩展,例如增加动态扩容、支持自定义数据类型等功能。掌握字典的原理和实现方法,对于成为一名优秀的程序员具有重要意义。