aboutsummaryrefslogtreecommitdiff
path: root/src/graph.c
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/graph.c46
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);
}