I'm currently working on an assignment to implement Prim's and Dijkstra's algorithms with graphs, but I got hung up trying to implement some basic graph functions based on this header:
//APIs for graph representation by adjacency list
typedef struct ADJNODE { //adjacency node
int vertex;
int weight;
struct ADJNODE *next;
} adjnode;
typedef struct GRAPH {
int vn; //number of nodes
adjnode **adjlist; //pointer to an array of pointers of neighbors
} graph;
graph *new_graph(int n);
void add_edge(graph *g, int from, int to, int weight);
int get_weight(graph *g, int from, int to);
void display_graph(graph *g);
void delete_graph(graph *g);
(Note that I can't change the structs or function headers as they were specified this way in my assignment.)
I'm having trouble getting add_edge
to work correctly.
My code for it so far:
void add_edge(graph *g, int from, int to, int weight) {
adjnode *n = g->adjlist[from];
adjnode *current = n, *prev;
prev = NULL;
while (current != NULL) {
prev = current;
current = current->next;
}
current = malloc(sizeof(struct adjnode*));
current->next = NULL;
current->vertex = to;
current->weight = weight;
if (prev != NULL)
prev->next = current;
else
g->adjlist[from] = current;
return;
}
My problem is that when I try to print all the edges (by moving to a point in adjlist
and then cycling through that adjnode
s next's like a linked-list) I find that every node in adjlist
is NULL
(if I'm traversing it correctly). I'm not sure if my function isn't actually connecting the new adjnode
s to the original graph g
or if I'm severely misunderstanding how adjlist
is supposed to be used.
I'm assuming adjnode **adjlist
works as a pointer to an array of adjnode
pointers, which are essentially all heads of their own linked lists (because the number of nodes in adjlist
is set based on the number of vertexes in the graph, and I'm assuming the edges are added as "nexts" to each of those base nodes)
This is my professors implementation of the new_graph
function if it helps:
//API implementation for graph representation by adjacency list
graph *new_graph(int vertex_number) {
graph *gp = malloc(sizeof(graph));
adjnode **np = malloc(vertex_number * sizeof(adjnode*));
int i;
for (i = 0; i < vertex_number; i++) {
np[i] = NULL;
}
gp->vn = vertex_number;
gp->adjlist = np;
return gp;
}
Note that I'm basing my understanding of adjlist
on how he's used the variable np
in the for
loop.
*Edit
- added some code as suggested in the comments to add_edge
Also, I've noticed the program crashes after calling it a few times:
graph *graph = new_graph(5); //total of 5 vertices (0,1,2,3,4)
add_edge(graph, 0, 1, 7);
add_edge(graph, 1, 0, 7);
add_edge(graph, 0, 2, 3);
add_edge(graph, 2, 0, 3);//crashed here
Based on some output statements it seems to crash right before
current = malloc(sizeof(struct adjnode*));
, I'm not sure what's causing that.