// Returns whether `from` has a direct edge or arc to `to`. // // Args: // graph: adjacency-list graph to query. // from: start vertex index. // to: end vertex index. // // Returns: // true if `to` appears in `from`'s adjacency list; false otherwise. boolAdjacent(const ALGraph *graph, int from, int to) { // 邻接表不能像邻接矩阵那样 O(1) 定位 edge[from][to]。 // 必须沿 from 的链表查找,看是否存在邻接点 to。 for (ArcNode *arc = graph->vertices[from].firstArc; arc != NULL; arc = arc->next) { if (arc->adjvex == to) { returntrue; } }
returnfalse; }
// Inserts one arc node into `from`'s adjacency list. // // Args: // graph: adjacency-list graph to modify. // from: start vertex index; the new node is inserted into this list. // to: end vertex index; stored as the new node's adjvex. // weight: edge or arc weight. // // Side effects: // Allocates one ArcNode and inserts it at the head of `from`'s list. voidAddArc(ALGraph *graph, int from, int to, int weight) { ArcNode *arc = malloc(sizeof(ArcNode)); if (arc == NULL) { return; } arc->adjvex = to; arc->weight = weight;
// Adds one edge or arc. // // Args: // graph: adjacency-list graph to modify. // from: start vertex index. // to: end vertex index. // weight: edge or arc weight. // // Side effects: // For a directed graph, inserts only <from, to>. For an undirected graph, // inserts both from -> to and to -> from. voidAddEdge(ALGraph *graph, int from, int to, int weight) { // 有向图中,这一句插入弧 <from, to>。 AddArc(graph, from, to, weight);
if (!graph->directed) { // 无向边 (from, to) 要在两个端点的链表中各存一次。 AddArc(graph, to, from, weight); }
++graph->edgeCount; } // Returns the out-degree of `vertex`. // // Args: // graph: adjacency-list graph to query. // vertex: vertex index. // // Returns: // Length of `vertex`'s adjacency list. For an undirected graph, this is the // ordinary degree. intOutDegree(const ALGraph *graph, int vertex) { int degree = 0;
// Returns the in-degree of `vertex`. // // Args: // graph: adjacency-list graph to query. // vertex: vertex index. // // Returns: // Number of arc nodes in the whole graph whose adjvex equals `vertex`. intInDegree(const ALGraph *graph, int vertex) { int degree = 0;
// 入边不在 vertex 自己的链表中,而是散落在其他顶点的出边表里。 // 因此必须扫描整个邻接表,统计哪些弧的终点是 vertex。 for (int i = 0; i < graph->vertexCount; ++i) { for (ArcNode *arc = graph->vertices[i].firstArc; arc != NULL; arc = arc->next) { if (arc->adjvex == vertex) { ++degree; } } }
// Inserts one arc node at the tail, using ordinary pointers. // // Args: // graph: adjacency-list graph to modify. // from: start vertex index; the new node is inserted into this list. // to: end vertex index; stored as the new node's adjvex. // weight: edge or arc weight. // // Side effects: // Appends one ArcNode. This preserves the input order of adjacent vertices. voidAddArc(ALGraph *graph, int from, int to, int weight) { ArcNode *arc = malloc(sizeof(ArcNode)); if (arc == NULL) { return; }