-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmap.c
More file actions
135 lines (119 loc) · 2.67 KB
/
map.c
File metadata and controls
135 lines (119 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/**
* Copyright © https://github.com/microwind All rights reserved.
* @author: [email protected]
* @version: 1.0
* @description: 映射数据结构 - C实现
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INITIAL_CAPACITY 10 // 初始容量
// Map 结构体
typedef struct
{
char *key;
int value;
} Entry;
typedef struct
{
Entry *entries;
int size;
int capacity;
} Map;
// 初始化 Map
void initMap(Map *map)
{
map->size = 0;
map->capacity = INITIAL_CAPACITY;
map->entries = (Entry *)malloc(map->capacity * sizeof(Entry));
}
// 重新分配容量
void resizeMap(Map *map, int newCapacity)
{
map->capacity = newCapacity;
map->entries = (Entry *)realloc(map->entries, map->capacity * sizeof(Entry));
}
// 插入键值对(如果存在则更新)
void put(Map *map, const char *key, int value)
{
for (int i = 0; i < map->size; i++)
{
if (strcmp(map->entries[i].key, key) == 0)
{
map->entries[i].value = value; // 更新值
return;
}
}
if (map->size >= map->capacity)
{
resizeMap(map, map->capacity * 2);
}
map->entries[map->size].key = strdup(key);
map->entries[map->size].value = value;
map->size++;
}
// 查找键
int get(Map *map, const char *key, int *found)
{
for (int i = 0; i < map->size; i++)
{
if (strcmp(map->entries[i].key, key) == 0)
{
*found = 1;
return map->entries[i].value;
}
}
*found = 0;
return -1; // 未找到
}
// 删除键
void delete(Map *map, const char *key)
{
for (int i = 0; i < map->size; i++)
{
if (strcmp(map->entries[i].key, key) == 0)
{
free(map->entries[i].key);
for (int j = i; j < map->size - 1; j++)
{
map->entries[j] = map->entries[j + 1];
}
map->size--;
return;
}
}
}
// 释放 Map
void freeMap(Map *map)
{
for (int i = 0; i < map->size; i++)
{
free(map->entries[i].key);
}
free(map->entries);
}
// 测试
int main()
{
Map map;
initMap(&map);
put(&map, "apple", 10);
put(&map, "banana", 20);
put(&map, "orange", 30);
int found;
printf("apple: %d\n", get(&map, "apple", &found));
printf("banana: %d\n", get(&map, "banana", &found));
printf("grape: %d (not found)\n", get(&map, "grape", &found));
delete (&map, "banana");
printf("banana after delete: %d\n", get(&map, "banana", &found));
freeMap(&map);
return 0;
}
/*
jarry@MacBook-Pro map % gcc map.c
jarry@MacBook-Pro map % ./a.out
apple: 10
banana: 20
grape: -1 (not found)
banana after delete: -1
*/