2-2 设具有n个顶点的有向图用邻接表存储(不存在逆邻接表)。试写出计算所有顶点入度的算法,将每个顶点的入度值分别存入一维数组 int Indegree[n]中C语言
时间: 2024-05-10 18:19:33 浏览: 86
以下是计算所有顶点入度的算法,将每个顶点的入度值分别存入一维数组 int Indegree[n]中:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 100
typedef struct ArcNode {
int adjvex;
struct ArcNode *next;
} ArcNode;
typedef struct VNode {
ArcNode *firstarc;
} VNode, AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices;
int vexnum, arcnum;
} ALGraph;
void CreateGraph(ALGraph *G) {
printf("请输入有向图的顶点数和边数:\n");
scanf("%d%d", &G->vexnum, &G->arcnum);
printf("请输入有向图的各个顶点信息:\n");
for (int i = 0; i < G->vexnum; i++) {
G->vertices[i].firstarc = NULL;
}
printf("请输入有向图的各个边的信息:\n");
for (int i = 0; i < G->arcnum; i++) {
int v1, v2;
printf("请输入第%d条边的两个端点:\n", i + 1);
scanf("%d%d", &v1, &v2);
ArcNode *arc = (ArcNode *)malloc(sizeof(ArcNode));
arc->adjvex = v2;
arc->next = G->vertices[v1].firstarc;
G->vertices[v1].firstarc = arc;
}
}
void ComputeIndegree(ALGraph *G, int Indegree[]) {
for (int i = 0; i < G->vexnum; i++) {
Indegree[i] = 0;
}
for (int i = 0; i < G->vexnum; i++) {
ArcNode *arc = G->vertices[i].firstarc;
while (arc != NULL) {
int j = arc->adjvex;
Indegree[j]++;
arc = arc->next;
}
}
}
int main() {
ALGraph G;
CreateGraph(&G);
int Indegree[MAX_VERTEX_NUM];
ComputeIndegree(&G, Indegree);
printf("各个顶点的入度分别为:\n");
for (int i = 0; i < G.vexnum; i++) {
printf("%d ", Indegree[i]);
}
printf("\n");
return 0;
}
```
阅读全文