我正在尝试在图表中打印所有顶点及其边缘。我已经使用了图的邻接列表表示。我的代码是
#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);
}
答案 0 :(得分:0)
可能tmp!=NULL
从未发生过......?
答案 1 :(得分:0)
这可以永远循环for(tmp=arr[i];tmp!=NULL;tmp=tmp->next)
如果arr [i]它在一个循环中:保持一个被访问的向量来检查和中断循环,如:
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;
...
}
答案 2 :(得分:0)
n->next=arr[startVertex];
arr[startVertex]->next=n;
此代码使tmp!= NULL永远不会发生
也许是这样的:
n->next=arr[startVertex]->next;
arr[startVertex]->next=n;