我正在学习Skiena的《算法设计手册v3》。
我看到有些问题提到书中有一些拼写错误,但我不确定这是不是其中之一,或者只是因为我理解有误。
请考虑以下内容:
据我所了解,
下面这段代码让我感到困惑:
这个是怎么工作的?假设我的输入是
对于有向图,我期望得到类似于
我觉得
我看到有些问题提到书中有一些拼写错误,但我不确定这是不是其中之一,或者只是因为我理解有误。
请考虑以下内容:
typedef struct edgenode {
int y; /* adjacency info */
int weight; /* edge weight, if any */
struct edgenode *next; /* next edge in list */
} edgenode;
typedef struct {
edgenode *edges[MAXV+1]; /* adjacency info */
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;
void insert_edge(graph *g, int x, int y, bool directed) {
edgenode *p; /* temporary pointer */
p = malloc(sizeof(edgenode)); /* allocate edgenode storage */
p->weight = 0;
p->y = y;
p->next = g->edges[x];
g->edges[x] = p; /* insert at head of list */
g->degree[x]++;
if (!directed) {
insert_edge(g, y, x, true);
} else {
g->nedges++;
}
}
据我所了解,
void insert_edge(graph *g, int x, int y, bool directed)
函数通过将节点x
和y
添加到edges
数组中,连接了数组索引处的两个节点。下面这段代码让我感到困惑:
p->y = y;
p->next = g->edges[x];
g->edges[x] = p; /* insert at head of list */
这个是怎么工作的?假设我的输入是
x = 3, y = 4
,而且这是第一个输入。对于有向图,我期望得到类似于
3 -> 4
的结果。
p->y = y;
很好理解,x
的邻接点是y
。p->next = g->edges[x];
但是edges
数组被初始化为 null。这样会导致3.next == NULL
而不是3.next == 4
,对吗?g->edges[x] = p;
什么?edges[x] == x Node
,这让我感到困惑。
我觉得
p.next = y;
和y.next = NULL
现在是这样的,也就是第一次插入。也许是因为我对C语言有点生疏,需要一些帮助。
edges
是一个链表。那部分只是将其添加到该链表的前面。.next
实际上是边缘链表中的下一条边。(另外,我认为x
以某种方式被隐含了。也许这个链表稍后会转换成数组,并且x
是从数组索引中隐含的?) - Ouroborusedges
不是一个链表,而是一个(固定大小的)数组。在更深层次上有链表:edges[0]
、edges[1]
等都是链表(即指向这些链表第一个节点的指针),新的edgenode
节点会被添加到这些链表的开头,也就是说头部始终是最新添加的节点,因此每次插入都需要更新edges[x]
。 - trincot