我正在尝试打印图中的所有顶点及其边。我已经使用了邻接列表表示图。我的代码是
#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);
}
可能是tmp!=NULL
从未发生过?
n->next=arr[startVertex];
arr[startVertex]->next=n;
这段代码使tmp=NULL从不发生
可能是这样的:
n->next=arr[startVertex]->next;
arr[startVertex]->next=n;
如果arr[i]在循环内,这可能会永远循环for(tmp=arr[i];tmp!=NULL;tmp=tmp->next)
:保持一个被访问的向量来检查和中断循环,类似于:
node *visited[MAX];
int nVis = 0;
bool cycle = false;
for(tmp=arr[i];tmp!=NULL && !cycle;tmp=tmp->next) {
for (int j = 0; j < nVis; ++j)
if (visited[j] == tmp) {
cycle = true;
break;
}
visited[nVis++] = tmp;
...
}