哈希表删除元素代码c
时间: 2024-03-26 15:31:16 浏览: 16
以下是C语言中删除哈希表元素的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义哈希表节点结构
typedef struct Node {
int key;
char value[100];
struct Node* next;
} Node;
// 定义哈希表结构
typedef struct HashTable {
int size;
Node** table;
} HashTable;
// 创建哈希表
HashTable* createHashTable(int size) {
HashTable* hashTable = (HashTable*)malloc(sizeof(HashTable));
hashTable->size = size;
hashTable->table = (Node**)malloc(sizeof(Node*) * size);
memset(hashTable->table, 0, sizeof(Node*) * size);
return hashTable;
}
// 哈希函数
int hash(int key, int size) {
return key % size;
}
// 插入元素到哈希表
void insert(HashTable* hashTable, int key, char* value) {
int index = hash(key, hashTable->size);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = key;
strcpy(newNode->value, value);
newNode->next = NULL;
if (hashTable->table[index] == NULL) {
hashTable->table[index] = newNode;
} else {
Node* current = hashTable->table[index];
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 删除元素从哈希表
void removeElement(HashTable* hashTable, int key) {
int index = hash(key, hashTable->size);
Node* current = hashTable->table[index];
Node* prev = NULL;
while (current != NULL && current->key != key) {
prev = current;
current = current->next;
}
if (current == NULL) {
printf("Element not found\n");
return;
}
if (prev == NULL) {
hashTable->table[index] = current->next;
} else {
prev->next = current->next;
}
free(current);
}
// 销毁哈希表
void destroyHashTable(HashTable* hashTable) {
for (int i = 0; i < hashTable->size; i++) {
Node* current = hashTable->table[i];
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
}
free(hashTable->table);
free(hashTable);
}
int main() {
HashTable* hashTable = createHashTable(10);
// 插入元素到哈希表
insert(hashTable, 1, "apple");
insert(hashTable, 2, "banana");
// 删除元素从哈希表
removeElement(hashTable, 1);
// 销毁哈希表
destroyHashTable(hashTable);
return 0;
}
```