如何在C中创建有向图的邻接列表?

编辑:没有人回答,但我认为这与我如何存储我的列表有关。 现在我将每个顶点存储在一个名为G的节点数组中。但是我认为我需要使它成为一个二维数组,以便我不会覆盖其他节点中的数据。 (这很令人困惑)

正如标题所说,我正在尝试创建有向图。 我遇到了一个问题,每当我尝试将一个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[Ec] //Here we make sure new node points to child of our edge new->vertex = Ep 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; se); s++){ buffer = buffer->next; } new->vertex = Ec; buffer->next = new; } } 

Interesting Posts