【发布时间】:2015-08-15 12:04:21
【问题描述】:
我已经为基于 c 图形的小型实现编写了代码,并相应地列出了图形顶点的邻接列表。我上面的代码是:
#include<stdio.h>
#include<stdlib.h>
struct node {
int info;
struct node* next;
}* z, *adjv[50], *t;
void insert() {
int j, v, e, c, d, i;
z = (struct node*)malloc(sizeof(struct node));
z->next = z;
scanf("%d%d", &v, &e);
for (j = 1; j <= v; j++) {
adjv[j] = z;
}
for (j = 1; j <= e; j++) {
scanf("%d%d", &c, &d);
t = (struct node*)malloc(sizeof(struct node));
t->info = c;
t->next = adjv[d];
adjv[d] = t;
t = (struct node*)malloc(sizeof(struct node));
t->info = d;
t->next = adjv[c];
adjv[c] = t;
}
for (i = 1; i <= e; i++) {
while (adjv[i] != z) {
printf("%d", adjv[i]->info);
adjv[i] = adjv[i]->next;
}
}
}
int main() {
insert();
return 0;
}
当我为其提供顶点 =4 边 = 2 和边为 (1,2) (3,4) 时,它不会将其显示为断开连接的图,因为邻接列表仅显示 1 和 2 的值。请帮助我正在纠正这个问题,以便可以显示正确的邻接列表
【问题讨论】:
-
不要使用please、Thanks之类的句子,因为这只会让人不得不阅读更多(没有有价值的内容)。也使用适当的代码缩进。
-
C 中的数组索引从 0 开始。您始终使用基于 1 的索引并且您的数组应该足够大,但是如果您使用 C 编程,请使用 C 表示法。也没有必要创建一个虚拟哨兵节点;
NULL指针旨在承担该角色。 -
是的,但是代码适用于连接的组件,例如 when v=3 e=2 (1,2)( 2,3)
标签: c graph-algorithm