正如标题所说,我试图创建有向图。我遇到了一个问题,每当我尝试将一个Node添加到顶点的邻接列表时,它就会改变前一个顶点的列表。例如,我有一个带有这些边的简单有向图。 (父母,孩子)
(2,1)
(3,2)
(3,4)
(5,1)
当我尝试将顶点4添加到顶点3的邻接列表时,我最终改变了顶点2指向的顶点。我需要它从3 - > 2 - > 4没有改变顶点2.我不知道如何做到这一点。这是我的代码
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;
}
在上一个函数中调用下一个函数。注意:在插入E中表示单个边,而在create_graph中E表示所有边的列表
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;
}
}