我正在尝试在图中打印所有顶点及其边缘。我已经为图表使用了邻接表表示。我的代码是
#define MAX 1000
struct node
{
int data;
struct node *next;
};
struct node *arr[MAX];
void printGraph(int n)
{
// n is the number of vertex
int i;
for(i=0;i<n;i++)
{
printf("The vertex %d is connected to");
if(arr[i]->next==NULL)
printf("no edges");
else
{
struct node *tmp;
for(tmp=arr[i];tmp!=NULL;tmp=tmp->next)
printf("%d",tmp->data);
}
printf("\n");
}
}
每当我调用该printGraph
方法时,我的程序都会进入无限循环。错误可能在哪里?
I am adding my other methods. Please check them to see if I am properly creating a graph
void createEmptyGraph(int n)
{
// n is the number of vertices
int i;
for(i=0;i<n;i++)
{
struct node *n;
n=(struct node *)malloc(sizeof(struct node));
n->data=i;
n->next=NULL;
arr[i]=n;
}
printf("\nAn empty graph with %d vertices has been sreated",n);
printf("\nNo edge is connected yet");
}
void addNode(int startVertex,int endVertex)
{
// For directed edges
struct node *n;
n=(struct node *)malloc(sizeof(struct node));
n->next=arr[startVertex];
arr[startVertex]->next=n;
printf("\nAn edge between directed from %d to %d has been added",startVertex,endVertex);
}