图邻接表实现(C)
Graph Adjacency List Implementation (C)
我正在尝试使用以下定义在 C 中创建图形的相邻 ist 表示...
typedef struct edge
{
int to_vertex;
int weight;
} Edge;
typedef struct edgeNode
{
Edge edge;
struct edgeNode *next;
} *EdgeNodePtr;
typedef struct edgeList
{
EdgeNodePtr head;
} EdgeList;
typedef struct graph
{
int V;
EdgeList *edges;
} Graph;
创建图表并将所有值添加到图表的主要功能是
int numEdges;
int edgeToVertex;
int weight;
EdgeNodePtr new_node;
Graph G;
EdgeNodePtr current;
int *inDeg;
scanf("%d", &G.V);
G.edges = malloc(G.V * sizeof(EdgeList));
for (int i = 0; i < G.V; i++)
{
scanf("%d", &numEdges);
G.edges[i].head = NULL;
for (int j = 0; j < numEdges; j++)
{
new_node = malloc(sizeof(*new_node));
scanf("%d,%d", &edgeToVertex, &weight);
new_node->edge.to_vertex = edgeToVertex;
new_node->edge.weight = weight;
new_node->next = G.edges[i].head;
new_node = G.edges[i].head;
}
}
出于某种原因,我似乎无法弄清楚图表不会创建,我已经尝试触发它,它会添加一个节点,但该节点将始终相同。感谢任何帮助
这看起来很奇怪:
new_node->next = G.edges[i].head;
new_node = G.edges[i].head;
当您用 head
覆盖 new_node
时。
也许你想做:
new_node->next = G.edges[i].head;
G.edges[i].head = new_node;
使head
指向新节点。
我正在尝试使用以下定义在 C 中创建图形的相邻 ist 表示...
typedef struct edge
{
int to_vertex;
int weight;
} Edge;
typedef struct edgeNode
{
Edge edge;
struct edgeNode *next;
} *EdgeNodePtr;
typedef struct edgeList
{
EdgeNodePtr head;
} EdgeList;
typedef struct graph
{
int V;
EdgeList *edges;
} Graph;
创建图表并将所有值添加到图表的主要功能是
int numEdges;
int edgeToVertex;
int weight;
EdgeNodePtr new_node;
Graph G;
EdgeNodePtr current;
int *inDeg;
scanf("%d", &G.V);
G.edges = malloc(G.V * sizeof(EdgeList));
for (int i = 0; i < G.V; i++)
{
scanf("%d", &numEdges);
G.edges[i].head = NULL;
for (int j = 0; j < numEdges; j++)
{
new_node = malloc(sizeof(*new_node));
scanf("%d,%d", &edgeToVertex, &weight);
new_node->edge.to_vertex = edgeToVertex;
new_node->edge.weight = weight;
new_node->next = G.edges[i].head;
new_node = G.edges[i].head;
}
}
出于某种原因,我似乎无法弄清楚图表不会创建,我已经尝试触发它,它会添加一个节点,但该节点将始终相同。感谢任何帮助
这看起来很奇怪:
new_node->next = G.edges[i].head;
new_node = G.edges[i].head;
当您用 head
覆盖 new_node
时。
也许你想做:
new_node->next = G.edges[i].head;
G.edges[i].head = new_node;
使head
指向新节点。