C 如何在邻接列表中访问和循环?

C 如何在邻接列表中访问和循环?,c,traversal,adjacency-list,C,Traversal,Adjacency List,下面是我用来形成图形的邻接列表的实现。我不知道如何访问此列表并循环浏览以实现某些目标(例如DFS搜索) 我试图做一些类似于graph[I][j]的事情,但编译器会说这是一个错误 下标值既不是数组也不是指针 我认为这里的图表只是指向另一个列表的指针 我该怎么办 注意:我无法正确格式化代码,因此我选择使用粘贴箱,很抱歉给您带来不便 您的图形是指向图形对象的指针。该对象具有成员顶点,一个指向顶点对象的指针数组。因此,顶点位于图形->顶点,顶点#0将位于图形->顶点[0] 每个顶点都有一个成员第一条边

下面是我用来形成图形的邻接列表的实现。我不知道如何访问此列表并循环浏览以实现某些目标(例如DFS搜索)

我试图做一些类似于
graph[I][j]
的事情,但编译器会说这是一个错误

下标值既不是数组也不是指针

我认为这里的图表只是指向另一个列表的指针

我该怎么办

注意:我无法正确格式化代码,因此我选择使用粘贴箱,很抱歉给您带来不便


您的
图形
是指向
图形
对象的指针。该对象具有成员
顶点
,一个指向
顶点
对象的指针数组。因此,顶点位于
图形->顶点
,顶点#0将位于
图形->顶点[0]

每个顶点都有一个成员
第一条边
,它是指向其第一条边的指针。因此,顶点#0的第一条边是
图形->顶点[0]->第一条边
,其权重是,例如,在
图形->顶点[0]->第一条边->权重

邻接列表上的下一条边是第一条边的
下一条边
(例如,
图形->顶点[0]->第一条边->下一条边
)。要查找所有边,应使用
for
循环处理列表,从
图形->顶点[0]->第一条边开始,继续到
下一条边,直到
下一条边
为0

for(Edge *current = graph->vertices[0]->first_edge; 
    current;
    current = current->next_edge) {
    do_something_with(current);
}

希望有帮助。

请在此处发布您的代码,而不是发布代码链接。这是一种常见的礼貌。@Antoh格式化了代码,并按上述方式进行了更新。很抱歉给您带来不便。所以循环本身知道,如果下一条边碰到顶点的末端,它将自动停止?对不起,如果我听起来很傻。。。谢谢你的帮助!它真的在一起。没有什么事情是自动发生的。循环停止,因为条件
current
变为false。啊,我现在明白了!这是因为现在next_edge指向nothing(在本例中为0),所以循环不会正常运行?
#ifndef GRAPH_H
#define GRAPH_H

typedef struct graph Graph;
typedef struct vertex Vertex;
typedef struct edge Edge;

// a graph knows its order (number of vertices) and an array of pointers to
// those vertices.
// these values can be used, but should not be *modified* outside of graph.c. 
// they are read-only!
struct graph {
    int n, maxn;
    Vertex** vertices;
};

// a vertex has a label and a pointer to the first edge in its adjacency list.
// these values can be used, but should not be *modified* outside of graph.c. 
// they are read-only!
struct vertex {
    char* label;
    Edge* first_edge;
};

// an edge knows the IDs of its two incident vertices; from u, to v
// each edge also knows its weight, and points to the next edge in a list of
// edges from the same vertex (or to NULL if it's the last edge in the list).
// these values can be used, but should not be *modified* outside of graph.c. 
// they are read-only!
struct edge {
    int u, v;
    int weight;
    Edge* next_edge;
};

// create a new, empty graph, with space for a maximum of n vertices
Graph* new_graph(int n);

// destroy a graph, its vertices, and their edges
void free_graph(Graph* graph);


// add a new vertex with label 'name' to a graph
void graph_add_vertex(Graph* graph, const char* name);

// add an undirected edge between u and v with weight w to graph
void graph_add_u_edge(Graph* graph, int u, int v, int w);

// add a directed edge from u to v with weight w to a graph
void graph_add_d_edge(Graph* graph, int u, int v, int w);

#endif
for(Edge *current = graph->vertices[0]->first_edge; 
    current;
    current = current->next_edge) {
    do_something_with(current);
}