在哈希表中查找用户名相同和删除用户名相同的记录时,线性探测解决冲突,c语言实现
时间: 2024-02-22 12:55:07 浏览: 16
以下是一个简单的C语言实现,使用线性探测解决冲突的哈希表:
```c
#include <stdio.h>
#include <string.h>
#define SIZE 10
#define EMPTY "EMPTY"
#define DELETED "DELETED"
typedef struct {
char name[20];
int age;
} Record;
Record hashtable[SIZE];
void init() {
int i;
for (i = 0; i < SIZE; i++) {
strcpy(hashtable[i].name, EMPTY);
hashtable[i].age = -1;
}
}
int hash(char* name) {
int sum = 0;
int i;
for (i = 0; i < strlen(name); i++) {
sum += name[i];
}
return sum % SIZE;
}
void insert(char* name, int age) {
int index = hash(name);
int i;
for (i = 0; i < SIZE; i++) {
int j = (index + i) % SIZE;
if (strcmp(hashtable[j].name, EMPTY) == 0 || strcmp(hashtable[j].name, DELETED) == 0) {
strcpy(hashtable[j].name, name);
hashtable[j].age = age;
return;
}
}
printf("Hashtable is full!\n");
}
Record* find(char* name) {
int index = hash(name);
int i;
for (i = 0; i < SIZE; i++) {
int j = (index + i) % SIZE;
if (strcmp(hashtable[j].name, EMPTY) == 0) {
return NULL;
}
if (strcmp(hashtable[j].name, name) == 0) {
return &hashtable[j];
}
}
return NULL;
}
void delete(char* name) {
Record* record = find(name);
if (record == NULL) {
printf("Record not found!\n");
} else {
strcpy(record->name, DELETED);
record->age = -1;
}
}
int main() {
init();
insert("Alice", 20);
insert("Bob", 30);
insert("Charlie", 25);
Record* record = find("Bob");
if (record != NULL) {
printf("%s is %d years old.\n", record->name, record->age);
}
delete("Bob");
record = find("Bob");
if (record == NULL) {
printf("Bob not found.\n");
}
return 0;
}
```
在这个例子中,我们使用了一个大小为10的哈希表,并使用了“线性探测”来解决冲突。插入操作使用哈希函数计算键值的索引,然后在顺序地检查索引,直到找到一个空插槽来插入记录。查找操作也使用哈希函数计算键值的索引,然后在顺序地检查索引,直到找到匹配的键或空插槽。删除操作使用查找操作来查找要删除的记录,然后将其标记为已删除。当查找记录时,已删除的插槽被视为空插槽。