问题
EDIT: No one has answered yet but I think it has to do with how I'm storing my list. Right now I'm storing every vertex in an array of nodes called G. However I think I need to make it a two dimensional array in order for me not to overwrite data in other Nodes. (This is very confusing)
As the title says I'm trying to create a directed graph. I'm running into a problem where each time I try to add a Node to the adjacency list of a vertex it is altering a previous vertex's list. For example I have a simple directed graph with these edges. (Parent , Child)
(2,1)
(3,2)
(3,4)
(5,1)
When I try to add vertex 4 to the adjacency list of vertex 3 I end up changing what vertex 2 points to. I need it go from 3 -> 2 -> 4 without altering vertex 2. I'm at a loss for how to do this. Here is my code
Node* create_graph(Edge* E, int numbVertices, size_t size){
int i, j=0;
Node* G = (Node*)malloc(sizeof(Node) * numbVertices);
G[0].vertex = 0;
G[0].next = NULL;
for(i=1;i<numbVertices;i++){
G[i].e = 0;
G[i].vertex = i;
G[i].next = NULL;
for(j=0;j<size;j++){
if((E[j].p) == i){
/* If a parent vertex in the list of edges E matches i
*value we insert child vertex (E[j].c) of that edge
*into the adjacency list */
insert(i,G,E[j]);
}
}
}
return G;
}
This next function is called inside the previous function. NOTE: in insert E represents a single edge while in create_graph E represents a list of all edges
void insert(int i, Node* G, Edge E){
Node* buffer;
Node* new;
new=(Node*)malloc(sizeof(Node));
new->e = new->e + 1;
new->next = &G[E.c] //Here we make sure new node points to child of our edge
new->vertex = E.p
int s;
//If this is the first time the vertex is visited the
//adj list will be empty hence e will equal 0
if(G[i].e == 0){
G[i] = *new;
}
else{
/* When this condition is met it means the adj list is not empty
*and we need to go to the end of the list and add out child vertex
*The for loop executes e times which = number of items in adj list
*/
buffer = &G[i];
for(s=0; s< (new->e); s++){
buffer = buffer->next;
}
new->vertex = E.c;
buffer->next = new;
}
}
来源:https://stackoverflow.com/questions/40120088/how-to-create-an-adjacency-list-of-a-directed-graph-in-c