C语言里如何存储映射:使用数组、链表、哈希表等数据结构。 在实际编程中,C语言缺乏内置的高级数据结构,如映射(即键值对存储),但可以通过组合基本数据结构来实现映射功能。本文将详细探讨如何在C语言中存储映射,并介绍不同的方法和实现细节。
一、数组
1.1 使用结构体数组存储键值对
在C语言中,可以通过定义一个结构体来存储键值对,然后使用结构体数组实现映射。结构体数组的实现相对简单,适合小规模的数据存储。
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
char key[50];
int value;
} KeyValuePair;
KeyValuePair map[MAX_SIZE];
int size = 0;
void insert(char* key, int value) {
strcpy(map[size].key, key);
map[size].value = value;
size++;
}
int search(char* key) {
for (int i = 0; i < size; i++) {
if (strcmp(map[i].key, key) == 0) {
return map[i].value;
}
}
return -1; // Key not found
}
int main() {
insert("apple", 1);
insert("banana", 2);
printf("The value for 'apple' is: %dn", search("apple"));
return 0;
}
1.2 优点和缺点
优点:
- 简单易懂,易于实现。
- 适合存储小规模的数据。
缺点:
- 查找效率较低,为O(n)时间复杂度。
- 不适合存储大规模数据,插入和查找速度会变慢。
二、链表
2.1 使用链表存储键值对
链表是一种动态数据结构,可以更灵活地存储数据。通过链表可以实现映射功能,并且插入和删除操作更加高效。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
char key[50];
int value;
struct Node* next;
} Node;
Node* head = NULL;
void insert(char* key, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
strcpy(newNode->key, key);
newNode->value = value;
newNode->next = head;
head = newNode;
}
int search(char* key) {
Node* current = head;
while (current != NULL) {
if (strcmp(current->key, key) == 0) {
return current->value;
}
current = current->next;
}
return -1; // Key not found
}
int main() {
insert("apple", 1);
insert("banana", 2);
printf("The value for 'apple' is: %dn", search("apple"));
return 0;
}
2.2 优点和缺点
优点:
- 动态分配内存,灵活性更高。
- 插入和删除操作更高效。
缺点:
- 查找效率仍为O(n)时间复杂度。
- 需要额外的内存空间来存储指针。
三、哈希表
3.1 使用哈希表存储键值对
哈希表是一种通过哈希函数将键映射到特定位置的数据结构。哈希表的查找、插入和删除操作都非常高效,平均时间复杂度为O(1)。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
typedef struct Node {
char key[50];
int value;
struct Node* next;
} Node;
Node* hashTable[TABLE_SIZE];
unsigned int hash(char* key) {
unsigned int hashValue = 0;
for (int i = 0; key[i] != '