hashset c++
时间: 2023-11-03 15:22:06 浏览: 78
哈希集(HashSet)是C编程语言中的一种数据结构,用于存储一组唯一的元素。它使用哈希函数将元素映射到一个索引,从而实现快速的插入、删除和查找操作。
在C语言中,可以使用哈希集的实现来创建自己的集合数据结构。以下是一个简单的示例代码,展示了如何实现一个基于哈希集的集合:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 100
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct HashSet {
Node* buckets[SIZE];
} HashSet;
HashSet* createHashSet() {
HashSet* set = (HashSet*)malloc(sizeof(HashSet));
for (int i = 0; i < SIZE; i++) {
set->buckets[i] = NULL;
}
return set;
}
int hashFunction(int data) {
return abs(data) % SIZE;
}
void addToHashSet(HashSet* set, int data) {
int index = hashFunction(data);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (set->buckets[index] == NULL) {
set->buckets[index] = newNode;
} else {
Node* current = set->buckets[index];
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
bool isInHashSet(HashSet* set, int data) {
int index = hashFunction(data);
Node* current = set->buckets[index];
while (current != NULL) {
if (current->data == data) {
return true;
}
current = current->next;
}
return false;
}
void removeFromHashSet(HashSet* set, int data) {
int index = hashFunction(data);
Node* current = set->buckets[index];
Node* prev = NULL;
while (current != NULL) {
if (current->data == data) {
if (prev == NULL) {
set->buckets[index] = current->next;
} else {
prev->next = current->next;
}
free(current);
return;
}
prev = current;
current = current->next;
}
}
void printHashSet(HashSet* set) {
for (int i = 0; i < SIZE; i++) {
Node* current = set->buckets[i];
printf("Bucket %d: ", i);
while (current ! NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
}
int main() {
HashSet* set = createHashSet();
addToHashSet(set, 1);
addToHashSet(set, 2);
addToHashSet(set, 3);
printf("Is 2 in the hash set? %s\n", isInHashSet(set, 2) ? "Yes" : "No");
printf("Is 4 in the hash set? %s\n", isInHashSet(set, 4) ? "Yes" : "No");
removeFromHashSet(set, 2);
printf("Is 2 in the hash set? %s\n", isInHashSet(set, 2) ? "Yes" : "No");
printHashSet(set);
return 0;
}
```
这个示例代码展示了如何创建一个基于哈希集的集合数据结构,以及如何向集合中添加、删除和查找元素。在这个例子中,我们使用哈希函数将元素映射到索引,并使用链表解决哈希冲突。你可以根据需要修改代码来适应不同的数据类型和需求。