]> wirehaze git hosting - graph-theory.git/blob - graph/adj.c

wirehaze git hosting

initial commit
[graph-theory.git] / graph / adj.c
1 #include "adj.h"
2 #include <stdlib.h>
3 #include <errno.h>
4
5 struct graph *
6 new_graph (unsigned int nv)
7 {
8 struct graph *g;
9
10 if (!nv)
11 return NULL;
12
13 if (!(g = malloc (sizeof *g)))
14 return NULL;
15
16 g->nv = nv;
17
18 if (!(g->v = calloc (nv, sizeof *g->v)))
19 {
20 free (g);
21 return NULL;
22 }
23
24 return g;
25 }
26
27 int
28 new_arc (struct graph *g, unsigned int vi, unsigned int vj)
29 {
30 struct edge *e;
31
32 if (vi >= g->nv || vj >= g->nv)
33 return -EINVAL;
34
35 if (!(e = malloc (sizeof *e)))
36 return -ENOMEM;
37
38 e->to = &g->v[vj];
39 e->next = g->v[vi].adj;
40 g->v[vi].adj = e;
41
42 return 0;
43 }
44
45 int
46 new_edge (struct graph *g, unsigned int vi, unsigned int vj)
47 {
48 int err;
49
50 if ((err = new_arc (g, vi, vj)))
51 return err;
52
53 if (vi != vj && (err = new_arc (g, vj, vi)))
54 return err; /* should delete the other arc but fuck it we ball */
55
56 return 0;
57 }