69,371
社区成员
发帖
与我相关
我的任务
分享
if(p->node[i]->firstarc==NULL)
{
p->node[j]->firstarc=m;
}
else
{
n->nextarc=m;
}
注意p->node[j],node[j]是野指针,需要为其分配空间才能进行这句操作p->node[j]->firstarc=m;否则会出现段错误;
while (1)
if (t->nextarc!=NULL)
{
printf ("%d\t",t->adivex);
t=t->nextarc;
}
else
{
printf ("%d\n",t->adivex);
//continue;
break;
}
}
这里的continue应改成break,否则这是一个死循环。
以下是我做的稍微修改,参考一下吧:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct st_arc
{
int adivex;
struct st_arc *nextarc;
} starc;
typedef struct head_node
{
int vexdata;
starc *firstarc;
}hnode;
typedef struct hnode_array
{
int num;
hnode node [6];
}hnarry;
void transfer (int (*A)[6],hnarry *p);
void output (hnarry *p);
int main ()
{
int i,j;
int A[6][6];
hnarry *p;
p=(hnarry *)malloc(sizeof (hnarry));
printf ("Please input the adjacency list:\n");
srand(time(NULL));
for (i=0;i<6;i++)
{
for (j=0;j<6;j++)
{
//scanf ("%d",&A[i][j]);
A[i][j] = rand() % 1000;
printf("%d\t", A[i][j]);
}
}
transfer (A,p);
output (p);
return 0;
}
void transfer (int (*A)[6],hnarry *p)
{
int i,j;
starc *m,*n;
p->num=0;
for (i=0;i<6;i++)
{
p->node[i].vexdata=i;
p->node[i].firstarc=NULL;
p->num++;
}
for (i=0;i<6;i++)
{
for (j=0;j<6;j++)
{
if(A[i][j]!=0)
{
m = (starc*)malloc(sizeof (starc));
m->adivex = A[i][j];
if(p->node[i].firstarc==NULL)
{
p->node[j].firstarc = m;
}
else
{
n->nextarc = m;
}
n=m;
n->nextarc=NULL;
}
}
}
}
void output (hnarry *p)
{
int i;
starc *t;
for (i=0;i<6;i++)
{
printf ("%d\n",p->node[i].vexdata);
if(p->node[i].firstarc!=NULL)
t = p->node[i].firstarc;
else
continue;
while (1)
if (t->nextarc!=NULL)
{
printf ("%d\t",t->adivex);
t=t->nextarc;
}
else
{
printf ("%d\n",t->adivex);
//continue;
break;
}
}
}