我已经为基于小型 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 的值。请帮助我正在纠正这个问题,以便可以显示正确的邻接列表
最佳答案
您需要更好地构建数据。例如,目前,边由struct node
表示,节点本身由指向struct node
的指针数组表示。
在您的代码中,adjv[i]
是顶点 i
邻接列表的头部,但您的代码会循环遍历边数。您有 4 个顶点和 2 条边,因此您错过了与顶点 3 和 4 的连接。
修正后的(更详细的)打印循环将循环到顶点数:
for (i = 1; i <= v; i++) {
while (adjv[i] != z) {
printf("%d -> %d\n", i, adjv[i]->info);
adjv[i] = adjv[i]->next;
}
}
也就是说,请考虑通过以下方式使您的代码更具可读性和更 C 风格:
- 使您的索引从零开始;
- 使用
NULL
指针作为链表的哨兵值; - 为顶点和边提供不同的结构,因为它们代表不同的事物并且通常也需要不同的数据;
- 始终使用
节点
或顶点
之一,因为它们本质上是相同的,但在代码中应该有一个统一的名称,以便您可以快速理解是什么正在进行中。
关于c 显示图的邻接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32024529/