【发布时间】:2021-12-01 05:00:19
【问题描述】:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct Graph* GraphList();
struct Listnode
{
int vertex;
struct Listnode*next;
};
struct Graph
{
int V;
int E;
struct Listnode *Adj;
};
void main()
{
struct Graph *G=NULL;
int i;
struct Listnode *temp=NULL;
printf("Program to Implement graph using Adjacency List\n");
G=GraphList();
for(i=0;i<G->V;i++)
{
temp=G->Adj+i;
while((temp->next)!=(G->Adj+i))
{
printf("%d-->",temp->vertex);
temp=temp->next;
}
printf("%d",temp->vertex);
printf("\n");
}
}
struct Graph* GraphList()
{
int i,j,x,y;
struct Listnode *t,*temp;
struct Graph *G;
G=(struct Graph*)malloc(sizeof(struct Graph));
printf("Enter the no.of vertices and Edges respectively\n");
scanf("%d %d",&G->V,&G->E);
G->Adj=(struct Listnode*)malloc((sizeof(struct Listnode))*G->V); //Undirected Graph
for(i=0;i<G->V;i++)
{
(G->Adj+i)->vertex=i+1;
(G->Adj+i)->next= (G->Adj+i);
}
for(i=0;i<G->V;i++)
{
t= (G->Adj+i);
printf("Enter number of neigbouring nodes to node-%d ",i+1);
scanf("%d",&x);
for(j=0;j<x;j++)
{
printf("Enter the vertex number-%d that is neighbour to node -%d ",j+1,i+1);
scanf("%d",&y);
temp=(struct Listnode*)malloc(sizeof(struct Listnode));
temp->vertex=y;
temp->next= G->Adj+i;
while(t->next!= (G->Adj+i))
t=t->next;
t->next=temp;
}
}
return G;
}
上面的代码工作正常,但是当我用“G->Adj[i]”替换“G->Adj+i”时它不起作用。我创建了“struct Listnode”类型的数组(比如说size-5)并将其存储在“G->Adj”中,我觉得使用“G->Adj[i]”是公平的,但我没有不明白为什么会弹出错误信息:
"D:\DataStructures by SS\Graph Link (standard).c|60|error: incompatible types when assigning to type 'struct Listnode *' from type 'struct Listnode'| ".
请解释一下。
【问题讨论】:
-
也许你需要有一个
Adj的双指针,比如struct Listnode **Adj;。所以它将是一个指向Listnodes 的动态指针数组。 -
第60行是哪一个?
-
G->Adj[i]返回元素,但需要元素的地址,可以使用&G->Adj[i]获取
标签: c data-structures graph adjacency-list