写一段C语言关键字的哈希表
时间: 2023-05-28 11:06:04 浏览: 108
以下是一段C语言关键字的哈希表:
```
#define HASH_SIZE 31
typedef struct {
char *key;
int value;
} HashNode;
HashNode *hashTable[HASH_SIZE];
void initHashTable() {
int i;
for (i = 0; i < HASH_SIZE; i++) {
hashTable[i] = NULL;
}
}
unsigned int hashFunction(char *key) {
unsigned int hash = 0;
while (*key) {
hash = (hash << 5) + hash + (*key++);
}
return hash % HASH_SIZE;
}
void insert(char *key, int value) {
unsigned int hash = hashFunction(key);
HashNode *node = (HashNode *) malloc(sizeof(HashNode));
node->key = key;
node->value = value;
node->next = hashTable[hash];
hashTable[hash] = node;
}
int get(char *key) {
unsigned int hash = hashFunction(key);
HashNode *node = hashTable[hash];
while (node) {
if (strcmp(node->key, key) == 0) {
return node->value;
}
node = node->next;
}
return -1;
}
void del(char *key) {
unsigned int hash = hashFunction(key);
HashNode *node = hashTable[hash];
HashNode *prev = NULL;
while (node) {
if (strcmp(node->key, key) == 0) {
if (prev) {
prev->next = node->next;
} else {
hashTable[hash] = node->next;
}
free(node);
return;
}
prev = node;
node = node->next;
}
}
```
这段代码定义了一个哈希表,用于存储C语言关键字及其对应的值。其中,哈希表大小为31,哈希函数使用了BKDR算法,冲突解决采用了链地址法。可以通过调用insert()函数向哈希表中插入数据,调用get()函数查询数据,调用del()函数删除数据。
阅读全文