From 36fa8aa09bbcd04d1c07c1324b568580c0ab89f1 Mon Sep 17 00:00:00 2001 From: laentropia Date: Wed, 6 May 2026 20:39:10 -0600 Subject: [PATCH] addition: add and connect vertex --- src/graph.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/graph.c b/src/graph.c index 6fa8f88..c7c08df 100644 --- a/src/graph.c +++ b/src/graph.c @@ -1,8 +1,10 @@ #include "graph.h" #include "arraylist.h" #include +#include #include #include +#include struct Vertex { ArrayList *edges; @@ -50,5 +52,49 @@ GraphErr graph_destroy(Graph **graph) { arraylist_destroy(&(*graph)->vertices); + *graph = NULL; + + return GRAPH_OK; +} + +GraphErr graph_add_vertex(Graph *graph) { + if (graph == NULL) { + return GRAPH_NULL_ARG; + } + + Vertex new_vertex = {.edges = arraylist_init(16, sizeof(Edge))}; + + arraylist_push_back(graph->vertices, &new_vertex); + + return GRAPH_OK; +} + +GraphErr graph_connect_vertex( + Graph *graph, + size_t node1, + size_t node2, + size_t weight) { + if (graph == NULL) { + return GRAPH_NULL_ARG; + } + + size_t vertex_count = arraylist_size(graph->vertices); + if (node1 >= vertex_count || node2 >= vertex_count) { + return GRAPH_VERTEX_NOT_FOUND; + } + + Edge new_edge = {.to = node2, .weight = weight}; + Vertex vertex1; + Vertex vertex2; + arraylist_get(graph->vertices, node1, &vertex1); + arraylist_get(graph->vertices, node2, &vertex2); + + arraylist_push_back(vertex1.edges, &new_edge); + + if (graph->type == GRAPH_UNDIRECTED) { + Edge inverse_edge = {.to = node1, .weight = weight}; + arraylist_push_back(vertex2.edges, &inverse_edge); + } + return GRAPH_OK; }