已知某有向图的邻接表,求该图各节点的入度和出度(C语言版)

#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 函数来计算各节点的入度和出度。最后,我们打印出各节点的入度和出度,并释放了动态分配的内存。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值