设具有n个顶点的有向图用邻接表存储(不存在逆邻接表)。试用c语言写出计算所有顶点入度的算法(不要伪代码),将每个顶点的入度值分别存入一维数组 int Indegree[n]中
时间: 2023-06-20 15:09:55 浏览: 91
以下是计算所有顶点入度的C语言算法实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXN 100
typedef struct ArcNode {
int adjvex;
struct ArcNode *next;
} ArcNode;
typedef struct VertexNode {
int data;
ArcNode *firstarc;
} VertexNode, AdjList[MAXN];
typedef struct {
AdjList vertices;
int vexnum, arcnum;
} ALGraph;
int Indegree[MAXN];
void CreateGraph(ALGraph *G)
{
int i, j, k;
ArcNode *e;
printf("请输入总顶点数和总边数:\n");
scanf("%d%d", &G->vexnum, &G->arcnum);
printf("请依次输入各顶点的值:\n");
for (i = 0; i < G->vexnum; i++) {
scanf("%d", &G->vertices[i].data);
G->vertices[i].firstarc = NULL;
}
printf("请依次输入各边的起点和终点:\n");
for (k = 0; k < G->arcnum; k++) {
scanf("%d%d", &i, &j);
e = (ArcNode *)malloc(sizeof(ArcNode));
e->adjvex = j;
e->next = G->vertices[i].firstarc;
G->vertices[i].firstarc = e;
}
}
void CalcIndegree(ALGraph *G)
{
int i, j;
ArcNode *p;
for (i = 0; i < G->vexnum; i++) {
Indegree[i] = 0;
}
for (i = 0; i < G->vexnum; i++) {
p = G->vertices[i].firstarc;
while (p != NULL) {
Indegree[p->adjvex]++;
p = p->next;
}
}
}
int main()
{
ALGraph G;
int i;
CreateGraph(&G);
CalcIndegree(&G);
printf("各顶点的入度为:\n");
for (i = 0; i < G.vexnum; i++) {
printf("%d ", Indegree[i]);
}
printf("\n");
return 0;
}
```
首先定义了邻接表存储有向图的数据结构,包括了图的总顶点数、总边数,各顶点的值和每个顶点的第一个邻接点。然后通过输入总顶点数、总边数、各顶点的值和各边的起点和终点创建有向图。最后遍历邻接表计算各顶点的入度,并将结果存储到一维数组中。
阅读全文