我有问题,以正确的顺序创建相邻的列表。我认为CreateAdjList(Void)方法存在一些问题。我的想法用完了。请给我一些提示。基本上我有图并在连通边上创建邻接列表。
#include <stdio.h>
#include <stdlib.h>
#define maxV 100
typedef struct graphnode{
int vertex;
struct graphnode *next;
}Node;
Node **node;
Node **nodeT;
FILE *fp;
void initial(int nv);
void AdjList(void);
void PrintAdjList(int nv);
int main()
{
int nv;
fp= fopen("input.txt","r");
fscanf(fp,"%d",&nv);
initial(nv);
CreateAdjList();
PrintAdjList(nv);
return 0;
}
void initial(int nv)
{
int i;
node = new Node *[maxV];
for(i=1;i<=nv;i++){
node[i] = (Node *)malloc(sizeof(Node));
node[i]->next=NULL;
}
}
//CREATE ADJACENCY LIST -
void CreateAdjList(void)
{
int v1,v2;
Node *ptr;
while(fscanf(fp,"%d%d",&v1,&v2)!=EOF){
ptr = (Node *)malloc(sizeof(Node));
ptr->vertex = v2;
ptr->next = node[v1]->next; //Problem could be here
node[v1]->next = ptr;
}
fclose(fp);
}
//PRINT LIST
void PrintAdjList(int nv)
{
int i;
Node *ptr;
for(i=1; i<=nv; i++){
ptr = node[i]->next;
printf(" node[%2d] ",i);
while(ptr != NULL){
printf(" -->%2d", ptr->vertex);
ptr=ptr->next;
}
printf("\n");
}
printf("\n");
}实际程序输出-错误的顺序。我以崇敬的方式附上了输出列表。
输入:
8
1 2
2 3
2 5
2 6
3 4
3 7
4 3
4 8
5 1
5 6
6 7
7 6
7 8
8 8
0 0
Expected Output:
Adjacency list represenation:
1: 2
2: 3 5 6
3: 4 7
4: 3 8
5: 1 6
6: 7
7: 6 8
8: 8我的实际输出显示错了顺序。如果您查看节点,正确的顺序应该是2 ->3->6->5。
node[ 1] --> 2
node[ 2] --> 6 --> 5 --> 3
node[ 3] --> 7 --> 4
node[ 4] --> 8 --> 3
node[ 5] --> 6 --> 1
node[ 6] --> 7
node[ 7] --> 8 --> 6
node[ 8] --> 8发布于 2011-12-02 10:22:39
因为我已经有一段时间没有做过C :)
你想要的是一些更像下面的注解那样的东西,有几个错误,我看不出它是如何工作的。如果文件的末尾是' 0‘,并且在循环中使用的是always 1->nv,那么就不会有节点元素,因此总是失败的。
在我的示例中,我保持数组稀疏(只分配实际存在的节点),同时满足其他条件。我也不在乎它们是什么顺序的,这样输入文件就可以无序了。还请注意,如果文件数据具有稀疏数据,则可能需要更新打印方法(即。第一个数字是10,它遗漏了任何类似‘9x’的东西。
void initial(int nv)
{
node = (Node **)malloc(maxV * sizeof(Node *));
}
//CREATE ADJACENCY LIST -
void CreateAdjList(void)
{
int v1,v2;
Node *ptr;
while(fscanf(fp,"%d %d",&v1,&v2)!=EOF){
ptr = (Node *)malloc(sizeof(Node));
ptr->vertex = v2;
if (node[v1]==NULL) {
node[v1] = (Node *)malloc(sizeof(Node));
node[v1]->vertex = v1;
node[v1]->next = NULL;
}
Node *next = node[v1];
while (next->next!=NULL)
next = next->next;
next->next = ptr;
//ptr->next = &(*(node[v1])->next); //Problem could be here
//node[v1]->next = ptr;
}
fclose(fp);
}发布于 2018-10-11 06:56:08
邻接表可以非常有效地表示一个图。它维护列表的顶点索引数组,以表示图的边和顶点,如下图所示:

阵列ArrayList
ArrayList数组可用于实现图的邻接列表。下面是描述ArrayList阵列使用的程序。
package com.vaibhav.graph;
import java.util.ArrayList;
public class Graph {
private final int V;
private ArrayList<Integer>[] adj;
public Graph(int V) {
this.V = V;
adj = new ArrayList[V];
for(int i=0; i < V; i++) {
adj[i] = new ArrayList<Integer>();
}
}
}https://stackoverflow.com/questions/8352212
复制相似问题