gpt4 book ai didi

c - 难以理解使用链表实现图的方法

转载 作者:行者123 更新时间:2023-11-30 16:51:55 26 4
gpt4 key购买 nike

我正在阅读一本关于算法的书,其中包含以下代码。我很难理解这里的一些台词。

我在以下代码中将我的疑问线显示为DOUBT LINE 1DOUBT LINE 2。我还将一行注释为REFERENCE,其中我很难理解。请详细说明DOUBT LINE 1DOUBT LINE 2

#define MAXV        100     /* maximum number of vertices */
#define NULL 0 /* null pointer */

/* DFS edge types */

#define TREE 0 /* tree edge */
#define BACK 1 /* back edge */
#define CROSS 2 /* cross edge */
#define FORWARD 3 /* forward edge */

typedef struct edgenode {
int y; /* adjancency info */
int weight; /* edge weight, if any */
struct edgenode *next; /* next edge in list */
} edgenode;

typedef struct {
edgenode *edges[MAXV+1]; /* adjacency info */ //REFERENCE
int degree[MAXV+1]; /* outdegree of each vertex */
int nvertices; /* number of vertices in the graph */
int nedges; /* number of edges in the graph */
int directed; /* is the graph directed? */
} graph;

它是 graph.h header ,其中还有读取和插入函数。

read_graph(graph *g, bool directed)
{
int i; /* counter */
int m; /* number of edges */
int x, y; /* vertices in edge (x,y) */

initialize_graph(g, directed);

scanf("%d %d",&(g->nvertices),&m);

for (i=1; i<=m; i++) {
scanf("%d %d",&x,&y);
insert_edge(g,x,y,directed);
}
}

insert_edge(graph *g, int x, int y, bool directed)
{
edgenode *p; /* temporary pointer */

p = malloc(sizeof(edgenode)); /* allocate storage for edgenode */

p->weight = NULL;
p->y = y;
p->next = g->edges[x]; //DOUBT LINE1

g->edges[x] = p; /* insert at head of list */ //DOUBT LINE 2

g->degree[x] ++;

if (directed == FALSE)
insert_edge(g,y,x,TRUE);
else
g->nedges ++;
}

最佳答案

每个顶点都有一组边。我们可以将集合视为无序的。在变元函数之外的任何时候,指针g->edges[i]都指向第i顶点上的第一个edgenode事件,或 NULL 否则。然后,edgenode 中的 next 链接可传递地指向集合中的其他边。

因此,要添加一条边,首先创建一条新边,然后将其 next 指针分配给当前“第一个”节点(DOUBT LINE 1),然后分配 g-> Edges[i] 指向新创建的值(怀疑线 2)。

请注意,我上面所说的需要存在的条件仍然满足,尽管节点的顺序发生了变化 - “以前”的第一个现在是第二个,新的节点是第一个。没关系,因为我们只是存储一组 - 顺序并不重要。

之前(=>遍历“下一个”链接):

   // edges[i] == <previous> => <other stuff>...

之后:

   //         *             *    These asterisks are above what we set...
//edges[i] == <new node> => <previous> => <other stuff>

关于c - 难以理解使用链表实现图的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41509239/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com