用邻接表实现某个点入度和出度

#include <cstdio>
#include <cstring>
#include <cctype>

using namespace std;

typedef struct node{//邻接表上的节点
    int n;
    struct node * next;
} GNode;

typedef struct graph{//图的整个结构
    int cn;//顶点个数
    int bn;//边的个数
    GNode *list;//顶点的数组相当于list[];
}Graph;//
void Init(Graph *G,int cn,int b)//对图初始化
{
    G->list= new GNode[cn];//
    //G->list=(GNode *)malloc(sizeof(GNode)*cn);
    G->bn=b;
    G->cn=cn;
    for(int i=0;i<cn;i++)
    {
        G->list[i].n=i;
        G->list[i].next=NULL;
    }
}
int get_OutDegree(Graph *G,int o)//
{
    int d=0;
    GNode *nde=G->list[o].next;
    while(nde)
    {
        d++;
        nde=nde->next;
    }
    return d;
}
int get_InDegree(Graph *G,int in)//
{
    int d=0;
    int n=G->cn;
    for(int i=0;i<n;i++)
    {
        GNode *nde = G->list[i].next;
        while(nde)
        {
            if(nde->n==in)  {d++;break;}
            nde =nde->next;
        }
    }
    return d;
}
void input(Graph *G)
{
    int a,b;
    int n=G->bn;
    printf("输入所有的边
");
    while(n--)
    {
        scanf("%d%d",&a,&b);//输入边,存储邻接表用的头插入法。
        GNode *T= new GNode();
        T->n =b;
        T->next = G->list[a].next;
        G->list[a].next=T;
    }

}
int main()
{
    int n,i,o,b;
    Graph *G= new Graph();
    scanf("%d%d",&n,&b);
    Init(G,n,b);
    input(G);
    printf("请输入计算出度的点(0~~~n-1):
");
    scanf("%d",&o);
    printf("%d
",get_OutDegree(G,o));
    printf("请输入计算入度的点(0~~~n-1):
");
    scanf("%d",&i);
    printf("%d
",get_InDegree(G,i));
}
原文地址:https://www.cnblogs.com/acmtime/p/6106148.html