addition: add and connect vertex

This commit is contained in:
2026-05-06 20:39:10 -06:00
parent d75adf8510
commit 36fa8aa09b

View File

@@ -1,8 +1,10 @@
#include "graph.h" #include "graph.h"
#include "arraylist.h" #include "arraylist.h"
#include <inttypes.h> #include <inttypes.h>
#include <stddef.h>
#include <stdint.h> #include <stdint.h>
#include <stdlib.h> #include <stdlib.h>
#include <sys/ucontext.h>
struct Vertex { struct Vertex {
ArrayList *edges; ArrayList *edges;
@@ -50,5 +52,49 @@ GraphErr graph_destroy(Graph **graph) {
arraylist_destroy(&(*graph)->vertices); 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; return GRAPH_OK;
} }