在头文件ljb.h中,更改头结点类型VertexNode(原头结点类型定义如下示),增加一个id数据域,用于标记结点的入度;编写一个函数void inDegree(LinkedGraph *g),用于计算有向图中每个结点的入度。编写主函数验证该函数的正确性。文件名称:computerInDegree.c
时间: 2024-03-22 09:42:10 浏览: 119
修改后的头文件ljb.h:
```c
#define MAX_VERTEX_NUM 20
typedef enum {DG, DN, UDG, UDN} GraphKind;
typedef struct ArcNode{
int adjvex;
struct ArcNode *nextarc;
// 增加一个权值域
int weight;
}ArcNode;
typedef struct VertexNode{
char data;
// 增加一个 id 数据域
int id;
ArcNode *firstarc;
}VertexNode, AdjList[MAX_VERTEX_NUM];
typedef struct{
AdjList vertices;
int vexnum, arcnum;
GraphKind kind;
}LinkedGraph;
```
computerInDegree.c:
```c
#include <stdio.h>
#include <stdlib.h>
#include "ljb.h"
void inDegree(LinkedGraph *g) {
// 初始化入度为 0
int indegree[g->vexnum];
for (int i = 0; i < g->vexnum; i++) {
indegree[i] = 0;
}
// 遍历邻接表,计算每个结点的入度
for (int i = 0; i < g->vexnum; i++) {
ArcNode *p = g->vertices[i].firstarc;
while (p != NULL) {
indegree[p->adjvex]++;
p = p->nextarc;
}
}
// 输出每个结点的入度
for (int i = 0; i < g->vexnum; i++) {
printf("Vertex %c (id: %d) has in-degree: %d\n", g->vertices[i].data, g->vertices[i].id, indegree[i]);
}
}
int main() {
LinkedGraph g;
// 构造图
g.vexnum = 5;
g.arcnum = 7;
g.kind = DG;
g.vertices[0].data = 'A';
g.vertices[0].id = 0;
g.vertices[0].firstarc = NULL;
g.vertices[1].data = 'B';
g.vertices[1].id = 1;
g.vertices[1].firstarc = NULL;
g.vertices[2].data = 'C';
g.vertices[2].id = 2;
g.vertices[2].firstarc = NULL;
g.vertices[3].data = 'D';
g.vertices[3].id = 3;
g.vertices[3].firstarc = NULL;
g.vertices[4].data = 'E';
g.vertices[4].id = 4;
g.vertices[4].firstarc = NULL;
ArcNode *a1 = (ArcNode*)malloc(sizeof(ArcNode));
a1->adjvex = 1;
a1->weight = 1;
a1->nextarc = g.vertices[0].firstarc;
g.vertices[0].firstarc = a1;
ArcNode *a2 = (ArcNode*)malloc(sizeof(ArcNode));
a2->adjvex = 3;
a2->weight = 1;
a2->nextarc = g.vertices[0].firstarc;
g.vertices[0].firstarc = a2;
ArcNode *a3 = (ArcNode*)malloc(sizeof(ArcNode));
a3->adjvex = 3;
a3->weight = 1;
a3->nextarc = g.vertices[1].firstarc;
g.vertices[1].firstarc = a3;
ArcNode *a4 = (ArcNode*)malloc(sizeof(ArcNode));
a4->adjvex = 2;
a4->weight = 1;
a4->nextarc = g.vertices[2].firstarc;
g.vertices[2].firstarc = a4;
ArcNode *a5 = (ArcNode*)malloc(sizeof(ArcNode));
a5->adjvex = 4;
a5->weight = 1;
a5->nextarc = g.vertices[2].firstarc;
g.vertices[2].firstarc = a5;
ArcNode *a6 = (ArcNode*)malloc(sizeof(ArcNode));
a6->adjvex = 3;
a6->weight = 1;
a6->nextarc = g.vertices[3].firstarc;
g.vertices[3].firstarc = a6;
ArcNode *a7 = (ArcNode*)malloc(sizeof(ArcNode));
a7->adjvex = 4;
a7->weight = 1;
a7->nextarc = g.vertices[3].firstarc;
g.vertices[3].firstarc = a7;
// 计算每个结点的入度
inDegree(&g);
return 0;
}
```
输出结果:
```
Vertex A (id: 0) has in-degree: 0
Vertex B (id: 1) has in-degree: 1
Vertex C (id: 2) has in-degree: 1
Vertex D (id: 3) has in-degree: 3
Vertex E (id: 4) has in-degree: 2
```
可以看到,每个结点的入度都被正确地计算出来了。
阅读全文