diff options
| author | Mikkel Thestrup <mithe24@student.sdu.dk> | 2025-12-01 10:30:03 +0100 |
|---|---|---|
| committer | Mikkel Thestrup <mithe24@student.sdu.dk> | 2025-12-01 10:30:24 +0100 |
| commit | f4ea7131029351cebc0a7de2e46d459dcb18b777 (patch) | |
| tree | b843752ae937f9da2ade6c10a94fdae7aca98cd3 /src/graph.c | |
| parent | c645866ceb7688b6b426144577d332c1d733b69d (diff) | |
| download | cycle-detector-f4ea7131029351cebc0a7de2e46d459dcb18b777.tar.gz cycle-detector-f4ea7131029351cebc0a7de2e46d459dcb18b777.zip | |
fixed inline if-else statements
Diffstat (limited to 'src/graph.c')
| -rw-r--r-- | src/graph.c | 46 |
1 files changed, 43 insertions, 3 deletions
diff --git a/src/graph.c b/src/graph.c index 4be2b44..cf45e2b 100644 --- a/src/graph.c +++ b/src/graph.c @@ -1,16 +1,56 @@ #include "graph.h" +#include "linked_list.h" #include <stdlib.h> +// Need to declare 'graph_delete' for use in 'graph_new' +void graph_delete(Graph *g); + Graph *graph_new(int n) { - Graph *graph = malloc(sizeof(Graph)); - if (!graph) return NULL; + Graph *graph = (Graph *)malloc(sizeof(Graph)); + if (!graph) + return NULL; + + graph->vertices = (Vertex *)malloc(sizeof(Vertex) * n); + if (!graph->vertices) { + free(graph); + return NULL; + } graph->numEdges = n; graph->numVertices = 0; - graph->vertices = malloc(sizeof(Vertex[n])); + + for (int i = 0; i < n; i++) { + graph->vertices[i].id = i; + graph->vertices[i].outNeighbours = linked_list_new(); + graph->vertices[i].inNeighbours = linked_list_new(); + + // if allocation for the linked lists failed + if (!graph->vertices[i].outNeighbours + || !graph->vertices[i].inNeighbours) { + graph_delete(graph); + return NULL; + } + } return graph; } void graph_add_edge(Graph *g, int i, int j) { + linked_list_append(g->vertices[i].outNeighbours, &g->vertices[j]); + linked_list_append(g->vertices[j].inNeighbours, &g->vertices[i]); + g->numEdges++; +} + +Graph *graph_read(const char *filename) { + Graph *g = graph_new(69); + return g; +} + +void graph_delete(Graph *g) { + for (int i = 0; i < g->numVertices; i++) { + linked_list_delete(g->vertices[i].inNeighbours); + linked_list_delete(g->vertices[i].outNeighbours); + } + free(g->vertices); + free(g); } |