#include <stdio.h>
#include <stdlib.h>
// 定义有向图的邻接表节点结构
typedef struct AdjListNode {
int dest;
struct AdjListNode* next;
} AdjListNode;
// 定义有向图的邻接表结构
typedef struct AdjList {
struct AdjListNode* head;
} AdjList;
// 定义有向图结构
typedef struct Graph {
int V; // 顶点数
struct AdjList* array;
} Graph;
// 创建有向图的邻接表节点
AdjListNode* createAdjListNode(int dest) {
AdjListNode* newNode = (AdjListNode*)malloc(sizeof(AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
// 创建有向图
Graph* createGraph(int V) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->V = V;
graph->array = (AdjList*)malloc(V * sizeof(AdjList));
for (int i = 0; i < V; ++i) {
graph->array[i].head = NULL;
}
return graph;
}
// 添加有向边到有向图
void addEdge(Graph* graph, int src, int dest) {
AdjListNode* newNode = createAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
}
// 计算有向图各节点的入度和出度
void calculateDegree(Graph* graph, int* inDegree, int* outDegree) {
for (int v = 0; v < graph->V; ++v) {
AdjListNode* node = graph->array[v].head;
while (node != NULL) {
outDegree[v]++; // 出度加1
inDegree[node->dest]++; // 入度加1
node = node->next;
}
}
}
int main() {
int V = 5; // 有向图的顶点数
Graph* graph = createGraph(V);
// 添加有向边到有向图
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 2, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);
// 初始化入度和出度数组
int* inDegree = (int*)calloc(V, sizeof(int));
int* outDegree = (int*)calloc(V, sizeof(int));
// 计算有向图各节点的入度和出度
calculateDegree(graph, inDegree, outDegree);
// 打印各节点的入度和出度
for (int v = 0; v < V; ++v) {
printf("Node %d: In-Degree = %d, Out-Degree = %d\n", v, inDegree[v], outDegree[v]);
}
// 释放内存
free(inDegree);
free(outDegree);
free(graph->array);
free(graph);
return 0;
}
在上面的示例中,我们首先定义了有向图的邻接表节点结构 AdjListNode
和邻接表结构 AdjList
,以及有向图结构 Graph
。然后,我们编写了函数来创建有向图的邻接表节点、创建有向图和添加有向边到有向图。最后,我们编写了函数 calculateDegree
来计算有向图各节点的入度和出度。
在 main
函数中,我们创建了一个有向图,并添加了一些有向边。然后,我们初始化了入度和出度数组,并调用 calculateDegree
函数来计算各节点的入度和出度。最后,我们打印出各节点的入度和出度,并释放了动态分配的内存。