【发布时间】:2015-01-14 09:32:45
【问题描述】:
我正在尝试使用图形的邻接表表示来表示图形。 我的代码编译正确但结果不正确,我似乎找不到合乎逻辑的 我的代码不一致。 这是一个示例输入和输出
Enter the number of Vertices
4
Enter the number of Edges
6
输入边缘
0 1
1 2
2 3
3 0
0 2
1 3
顶点0的邻接表 头 -> 0-> 2
顶点1的邻接表 头 -> 1-> 3
顶点2的邻接表 头 -> 2
顶点3的邻接表 头 -> 3
这里注意0也和1相连
2 也连接到 1 和 0
struct grnode {
long long num;
struct grnode *next;
};
struct graph {
long long v;
long long e;
struct grnode *adj;
};
struct graph *adjlistgr(){
long long i,x,y;
struct grnode *temp;
struct graph *g = (struct graph*)malloc(sizeof(struct graph));
if (!g) {
printf("memory error");
return;
}
// here we scanf the num of vertices and edges
printf("Enter the number of Vertices \n");
scanf("%lld", &g->v);
printf("Enter the number of Edges\n");
scanf("%lld", &g->e);
g->adj = malloc(g->v*sizeof(struct grnode));
for (i = 0; i < g->v; i++)
{
g->adj[i].num = i;
g->adj[i].next = &g->adj[i];
}
printf("Enter the Edges\n");
for (i = 0; i < g->e;i++)
{ // now we scan the edges
scanf("%lld %lld", &x,&y);
temp = (struct grnode*)malloc( sizeof( struct grnode*));
temp->num = y;
temp->next = &g->adj[x];
g->adj[x].next = temp;
temp = (struct grnode*)malloc( sizeof( struct grnode*));
temp->num = y;
temp->next = &g->adj[y];
g->adj[y].next = temp;
}return g;
}
void printgraph(struct graph* graph)
{
int n;
for (n = 0; n < graph->v; ++n)
{
// struct grnode *pCrawl = graph->adj[n].num;
struct grnode *temp;
temp = (struct grnode*)malloc( sizeof( struct grnode*));
temp->next=&graph->adj[n];
temp=temp->next;
printf("\n Adjacency list of vertex %d\n head ", n);
long long s=temp->num;
do
{
printf("-> %d", temp->num);
temp = temp->next;
}while(temp->num!=s);
printf("\n");
}}
int main(){
struct graph *mylist=adjlistgr();
printgraph(mylist);
}
【问题讨论】:
-
请注意这里 0 连接到 1 未显示是与代码不一致的地方之一
-
如果你想澄清你的问题,你应该编辑你的问题来做到这一点,而不是添加它作为评论。
-
当你
malloc(sizeof(struct grnode *))时,你需要malloc(sizeof(struct grnode))。为什么你malloc在一个jst打印数据的函数中(因此不应该修改任何东西)? -
我删除了 malloc 中的 * 它仍然可以正常工作,你能解释一下为什么必须删除它我是新手,所以我的基础知识有点不清楚
-
您为指针分配空间,通常为 4 或 8 个字节。您的数据类型需要空间,它是一个结构并且可能更大。 (但是,您分配给的句柄是一个指针,所以我可以看出您在哪里感到困惑。如果您坚持使用成语
Type *p = malloc(sizeof(*p)),通常是安全的。)
标签: c++ c graph adjacency-list