0

我正在尝试在图中打印所有顶点及其边缘。我已经为图表使用了邻接表表示。我的代码是

#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);
}
4

3 回答 3

0

可能tmp!=NULL永远不会发生……?

于 2012-07-19T09:17:27.920 回答
0

如果 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;
 ...
}
于 2012-07-19T09:21:49.227 回答
0
n->next=arr[startVertex];
arr[startVertex]->next=n;

此代码使 tmp!=NULL 永远不会发生

也许是这样的:

n->next=arr[startVertex]->next;
arr[startVertex]->next=n;
于 2012-07-19T09:23:28.163 回答