#include #include #include #include #include "graph.h" graph_t *graph_new() { graph_t *g = (graph_t*)malloc(sizeof(graph_t)); g->node_count = 0; g->edge_count = 0; g->edges = NULL; g->nodes = NULL; return g; } /** * Free a graph structure * DOES NOT free data */ void graph_free(graph_t *g) { int i; /* Free edges */ for(i=0; iedge_count; i++) free(g->edges[i]); free(g->edges); /* Free nodes */ for(i=0; inode_count; i++) free(g->nodes[i]); free(g->nodes); /* Free graph itself */ free(g); } /** * Add a node in the graph */ node_t *graph_node_add(graph_t *g, void *data) { /* Grow nodes ptr */ g->nodes = (node_t**)realloc(g->nodes, (g->node_count+1) * sizeof(node_t*)); node_t *node = g->nodes[g->node_count] = (node_t*)malloc(sizeof(node_t)); node->data = data; node->index = 0; /* Increment node count */ g->node_count++; return node; } /** * Create an edge */ edge_t *graph_edge_new(node_t *a, node_t *b, void *data) { edge_t *edge = (edge_t*)malloc(sizeof(edge_t)); edge->n1 = a; edge->n2 = b; edge->data = data; edge->index = 0; return edge; } /** * Free an edge */ void graph_edge_free(edge_t *e) { free(e); } /** * Add an edge between two nodes */ void graph_edge_add(graph_t *g, edge_t *edge) { /* Grow nodes ptr */ g->edges = (edge_t**)realloc(g->edges, (g->edge_count+1) * sizeof(edge_t*)); g->edges[g->edge_count] = edge; /* Increment edge count */ g->edge_count++; } /** * Visit all nodes by calling "f" on each */ void graph_node_visit(graph_t *g, void *data, void (*f)(graph_t*, node_t*, void *data)) { int i; for(i=0; inode_count; i++) f(g, g->nodes[i], data); } /** * Visit all edges by calling "f" on each */ void graph_edge_visit(graph_t *g, void *data, void (*f)(graph_t*, edge_t*, void *data)) { int i; for(i=0; iedge_count; i++) f(g, g->edges[i], data); } /** * Find a node based on its data * The comparator "f" should return : * - negative or 0 if not found * - positive if found */ node_t *graph_node_find(graph_t *g, void *data, int (*f)(node_t *n, void *data)) { int i; for(i=0; inode_count; i++) if ( f(g->nodes[i], data) > 0 ) return g->nodes[i]; return NULL; } /** * Find an edge based on its data * The comparator "f" should return : * - negative or 0 if not found * - positive if found */ edge_t *graph_edge_find(graph_t *g, void *data, int (*f)(edge_t *n, void *data)) { int i; for(i=0; iedge_count; i++) if ( f(g->edges[i], data) > 0 ) return g->edges[i]; return NULL; }