-sharpinclude<stdio.h>
-sharpinclude<stdlib.h>
-sharpinclude<time.h>
-sharpdefine V_NUM 10 //10
typedef struct node {
int num;
int index;
struct node *next;
} Node; //
typedef struct {
Node **v_arr; //
int size; //V_NUM
} G; //
void append(Node **l,Node *node)
{
Node *temp=*l;
while(temp->next)
{
temp=temp->next;
}
temp->next=node;
}
void Init(G *g)
{
g->size=V_NUM;
srand(time(NULL));
if(g->v_arr=(Node **)malloc(V_NUM*sizeof(Node *)))
{
Node *temp;
for(int i=0;i<V_NUM;iPP)
{
if(g->v_arr[i]=(Node *)malloc(sizeof(Node)))
{
g->v_arr[i]->num=rand()%15; //
g->v_arr[i]->index=i; //
g->v_arr[i]->next=NULL;
}
else
{
printf("Init v error!\n");
exit(1);
}
}
for(int i=0;i<V_NUM;iPP)
{
for(int j=0;j<V_NUM;jPP)
{
if(((g->v_arr[i]->num-g->v_arr[j]->num)%3==0||(i==0&&j<3)||(i==1&&j==0)||(i==2&&j==0))&&i!=j) //30-1,0-2
{
if(temp=(Node *)malloc(sizeof(Node)))
{
temp->num=g->v_arr[j]->num;
temp->index=g->v_arr[j]->index;
temp->next=NULL;
append(&g->v_arr[i],temp);
}
}
}
}
}
else
{
printf("Init error!\n");
exit(1);
}
}
void visit(Node *node)
{
printf("%d--%d ",node->index,node->num);
}
int visited[V_NUM]={0};
void __traverse(Node *l,void (*visit)(Node *))
{
visit(l);
visited[l->index]=1;
Node *temp;
for(temp=l->next;temp;temp=temp->next)
{
if(!visited[temp->index])
{
__traverse(temp,visit);
}
}
}
void traverse(G *g,void (*visit)(Node *)) //0
{
__traverse(g->v_arr[0],visit);
}
int main(void)
{
G g;
Init(&g);
for(int i=0;i<V_NUM;iPP)
{
for(Node *temp=g.v_arr[i];temp;temp=temp->next)
{
printf("%d--%d ",temp->index,temp->num);
}
putchar("\n");
}
putchar("\n");
traverse(&g,visit);
putchar("\n");
for(int i=0;i<V_NUM;iPP)
{
printf("%d ",visited[i]);
}
putchar("\n");return 0;
}
there is a problem with this code. Only the vertices connected to vertex 0 can be accessed. Please be kind-hearted to help point out the problem.