c 不通过键值清空hash 表 代码
时间: 2024-03-16 19:46:22 浏览: 15
以下是一个简单的 C 语言实现示例,用于清空哈希表,不需要使用键值:
```c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define HASH_TABLE_SIZE 100
struct node {
int key;
int value;
struct node* next;
};
struct hash_table {
struct node* table[HASH_TABLE_SIZE];
};
void clear_hash_table(struct hash_table* ht) {
for (int i = 0; i < HASH_TABLE_SIZE; i++) {
struct node* current = ht->table[i];
while (current != NULL) {
struct node* temp = current;
current = current->next;
free(temp);
}
ht->table[i] = NULL;
}
}
int main() {
struct hash_table ht;
memset(ht.table, 0, sizeof(ht.table));
// 向哈希表添加一些元素
for (int i = 0; i < HASH_TABLE_SIZE; i++) {
struct node* new_node = malloc(sizeof(struct node));
new_node->key = i;
new_node->value = i * 2;
new_node->next = ht.table[i];
ht.table[i] = new_node;
}
// 清空哈希表
clear_hash_table(&ht);
return 0;
}
```
在上面的示例中,我们使用了 `clear_hash_table()` 函数来清空哈希表,它能够有效地删除哈希表中所有的元素,而不需要使用键值。函数实现中,我们遍历哈希表,释放每个链表中的节点并将表项指针设置为 `NULL`。