-
Notifications
You must be signed in to change notification settings - Fork 747
/
set.c
48 lines (42 loc) · 1.12 KB
/
set.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
// Copyright 2014 Rui Ueyama. Released under the MIT license.
// Sets are containers that store unique strings.
//
// The data structure is functional. Because no destructive
// operation is defined, it's guranteed that a set will never
// change once it's created.
//
// A null pointer represents an empty set.
//
// Set is designed with simplicity in mind.
// It should be very fast for small number of items.
// However, if you plan to add a lot of items to a set,
// you should consider using Map as a set.
#include <stdlib.h>
#include <string.h>
#include "8cc.h"
Set *set_add(Set *s, char *v) {
Set *r = malloc(sizeof(Set));
r->next = s;
r->v = v;
return r;
}
bool set_has(Set *s, char *v) {
for (; s; s = s->next)
if (!strcmp(s->v, v))
return true;
return false;
}
Set *set_union(Set *a, Set *b) {
Set *r = b;
for (; a; a = a->next)
if (!set_has(b, a->v))
r = set_add(r, a->v);
return r;
}
Set *set_intersection(Set *a, Set *b) {
Set *r = NULL;
for (; a; a = a->next)
if (set_has(b, a->v))
r = set_add(r, a->v);
return r;
}