-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
120 lines (87 loc) · 2.58 KB
/
main.c
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
#include <stdlib.h>
#include <stdio.h>
#include "List.h"
#include "HashSet.h"
void * int_allocate(int n);
void int_print(void *i);
void * IntStrPair_allocate(int i, char *str, bool heapStr);
void IntStrPair_destruct(void * data);
void IntStrPair_print(void *pair);
size_t IntStrPair_hash(void *data);
bool IntStrPair_equal(void * a, void * b);
typedef struct {
int i;
char * str;
bool heapStr;
} IntStrPair;
int main()
{
List list = List_construct();
List_append(&list, int_allocate(5));
List_append(&list, int_allocate(10));
List_append(&list, int_allocate(8));
List_append(&list, int_allocate(2));
List_iterate(&list, int_print);
printf("\n");
List_dropHead(&list, free);
List_iterate(&list, int_print);
List_destruct(&list, free);
List_iterate(&list, int_print);
printf("\n");
HashSet map = HashSet_construct(IntStrPair_hash);
HashSet_insert(&map, IntStrPair_allocate(5, "five", false));
HashSet_insert(&map, IntStrPair_allocate(3, "three", false));
HashSet_insert(&map, IntStrPair_allocate(10, "ten", false));
HashSet_insert(&map, IntStrPair_allocate(110, "one hundred and ten", false));
HashSet_iterate(&map, IntStrPair_print);
printf("\n");
IntStrPair * three = HashSet_find(&map, IntStrPair_allocate(3, NULL, false),
IntStrPair_equal);
IntStrPair_print(three);
IntStrPair * ten = HashSet_find(&map, IntStrPair_allocate(10, NULL, false),
IntStrPair_equal);
IntStrPair_print(ten);
IntStrPair * oneTen = HashSet_find(&map, IntStrPair_allocate(110, NULL, false),
IntStrPair_equal);
IntStrPair_print(oneTen);
HashSet_destruct(&map, IntStrPair_destruct);
return 0;
}
void * int_allocate(int n)
{
int * i = malloc(sizeof(int));
*i = n;
return i;
}
void * IntStrPair_allocate(int i, char *str, bool heapStr)
{
IntStrPair * pair = malloc(sizeof(IntStrPair));
pair->i = i;
pair->str = str;
pair->heapStr = heapStr;
return pair;
}
void int_print(void *i)
{
printf("%d\n", *(int *)i);
}
void IntStrPair_print(void *pair)
{
IntStrPair * p = (IntStrPair *)pair;
printf("{ %d, %s }\n", p->i, p->str);
}
size_t IntStrPair_hash(void *data)
{
return (size_t)((IntStrPair *)data)->i;
}
void IntStrPair_destruct(void * data)
{
IntStrPair * pair = (IntStrPair *)data;
if (pair->heapStr)
free(pair->str);
free(pair);
}
bool IntStrPair_equal(void * a, void * b)
{
return ((IntStrPair *)a)->i == ((IntStrPair *)b)->i;
}