📅  最后修改于: 2023-12-03 14:40:26.840000             🧑  作者: Mango
在C程序中,计算数组中每个元素的频率可以使用哈希表(Hash Table)来实现。哈希表是一种数据结构,可以将一个给定的键(key)映射到一个数据(value)。
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 1000
struct node {
int key;
int value;
struct node* next;
};
struct hashtable {
struct node** array;
};
struct hashtable* hashtable_new() {
struct hashtable* ht = malloc(sizeof(struct hashtable));
ht -> array = malloc(sizeof(struct node*) * MAX_SIZE);
for (int i = 0; i < MAX_SIZE; i++) {
ht -> array[i] = NULL;
}
return ht;
}
void hashtable_insert(struct hashtable* ht, int key) {
int pos = key % MAX_SIZE;
if (ht -> array[pos] == NULL) {
ht -> array[pos] = malloc(sizeof(struct node));
ht -> array[pos] -> key = key;
ht -> array[pos] -> value = 1;
ht -> array[pos] -> next = NULL;
}
else {
struct node* ptr = ht -> array[pos];
while (ptr != NULL) {
if (ptr -> key == key) {
(ptr -> value)++;
return;
}
ptr = ptr -> next;
}
struct node* new_node = malloc(sizeof(struct node));
new_node -> key = key;
new_node -> value = 1;
new_node -> next = ht -> array[pos];
ht -> array[pos] = new_node;
}
}
void hashtable_print(struct hashtable* ht) {
for (int i = 0; i < MAX_SIZE; i++) {
if (ht -> array[i] != NULL) {
struct node* ptr = ht -> array[i];
while (ptr != NULL) {
printf("%d: %d\n", ptr -> key, ptr -> value);
ptr = ptr -> next;
}
}
}
}
int main() {
int a[] = {1, 2, 3, 4, 1, 2, 3, 4, 5};
int n = sizeof(a) / sizeof(a[0]);
struct hashtable* ht = hashtable_new();
for (int i = 0; i < n; i++) {
hashtable_insert(ht, a[i]);
}
hashtable_print(ht);
return 0;
}
1: 2
2: 2
3: 2
4: 2
5: 1
以上是一个简单的哈希表实现,通过该程序可以计算出输入数组中每个元素的频率。