图形邻接列表表示

时间:2012-07-18 18:22:29

标签: c

我正在尝试用c编写一个基本的图形程序。但是,会显示一条错误消息,指出The arrayOfVertices is undeclared。我使用邻接列表表示,代码是


#include <stdio.h>
#include <stdlib.h>

struct graphnode
{
int name;
struct graphnode *next;
};

void addNode(struct graphnode *G[],int startNode, int endNode)
{
// creating a new linked list which is to be added
struct graphnode *tmp;
tmp->name=endNode;
tmp->next=G[startNode];
startNode=tmp;
}

void printGraph(struct graphnode *G[], int numofnodes)
{
int i;
for(i=0;i<numofnodes;i++)
{
    struct graphnode *tmp;
    tmp=G[i];
    printf("%d",i);

    while(tmp!=NULL)
    {
        printf("%d",tmp->name);
        tmp=tmp->next;
    }
}
}

int main(void)
{
int numofnodes;
printf("Enter the number of nodes: ");
scanf("%d",&numofnodes);

// Note that we have created depending upon the size inputted by the user
struct graphnode *arrayOfVertices[numofnodes];
int i;      // for iteration

for(i=0;i<numofnodes;i++)
{
    arrayOfVertices[i]->name=i;
    arrayOfVertices[i]->next=NULL;
}

addNode(arrayOfVertices,0,1);
addNode(aarrayOfVertices,0,2);
printGraph(arrayOfVertices,numofnodes);

return 0;
}

我的方法是创建一个包含用户输入的节点的数组(struct graphnode类型)。该结构包含两个字段,一个包含数字,另一个包含指针。


1 个答案:

答案 0 :(得分:0)

--- graph.c 2012-07-18 21:33:52.405175347 +0200
+++ graph2.c    2012-07-18 21:40:01.150704287 +0200
@@ -1,3 +1,4 @@
+
 #include <stdio.h>
 #include <stdlib.h>

@@ -11,9 +12,10 @@
 {
 // creating a new linked list which is to be added
 struct graphnode *tmp;
+tmp = malloc (sizeof *tmp);
 tmp->name=endNode;
 tmp->next=G[startNode];
-startNode=tmp;
+G[startNode] = tmp;
 }

 void printGraph(struct graphnode *G[], int numofnodes)
@@ -22,13 +24,11 @@
 for(i=0;i<numofnodes;i++)
 {
     struct graphnode *tmp;
-    tmp=G[i];
     printf("%d",i);

-    while(tmp!=NULL)
+    for(tmp = G[i]; tmp; tmp = tmp->next)
     {
         printf("%d",tmp->name);
-        tmp=tmp->next;
     }
 }
 }
@@ -36,21 +36,24 @@
 int main(void)
 {
 int numofnodes;
+int i;
+struct graphnode **arrayOfVertices;
+
 printf("Enter the number of nodes: ");
 scanf("%d",&numofnodes);

 // Note that we have created depending upon the size inputted by the user
-struct graphnode *arrayOfVertices[numofnodes];
-int i;      // for iteration
+arrayOfVertices = malloc ( numofnodes * sizeof *arrayOfVertices);

 for(i=0;i<numofnodes;i++)
 {
+    arrayOfVertices[i] = malloc (sizeof *arrayOfVertices[i] );
     arrayOfVertices[i]->name=i;
     arrayOfVertices[i]->next=NULL;
 }

 addNode(arrayOfVertices,0,1);
-addNode(aarrayOfVertices,0,2);
+addNode(arrayOfVertices,0,2);
 printGraph(arrayOfVertices,numofnodes);

 return 0;

注意:我只发现了明显的错误。我用动态分配的数组替换了可变大小的数组。