假设不带权有向图采用邻接表G存储,设计实现以下功能的算法。
(1)求出图中每个顶点的出度。
(2)求出图中出度为0的顶点数。
(3)求出图中每个顶点的入度。
#include <iostream>
using namespace std;#define MVnum 100
typedef string VertexType;typedef struct ArcNode
{int adjvex;struct ArcNode* nextarc;int weight;
}ArcNode;typedef struct VNode
{VertexType data;struct ArcNode* firstarc;
}VNode, VNodeList[MVnum];typedef struct
{VNodeList vertices;int vexnum;int edgenum;
}Graph;int locatevex(Graph G, VertexType v)
{for (int i = 0; i < G.vexnum; i++){if (G.vertices[i].data == v) return i;}return -1;
}void CreateDG(Graph& G)
{int i = 0, j = 0;int k = 0;cout << "请输入总顶点数和总边数:";cin >> G.vexnum >> G.edgenum;cout << "输入顶点:";for (i = 0; i < G.vexnum; i++){cin >> G.vertices[i].data;G.vertices[i].firstarc = NULL;}for (int k = 0; k < G.edgenum; k++){VertexType v1, v2;cout << "输入第" << k + 1 << "条边:";cin >> v1 >> v2;i = locatevex(G, v1);j = locatevex(G, v2);ArcNode* p1 = (ArcNode*)malloc(sizeof(ArcNode));if (p1 == NULL){cout << "内存分配失败" << endl;exit(0);}p1->adjvex = j;p1->nextarc = G.vertices[i].firstarc;G.vertices[i].firstarc = p1;}
}/*--------将邻接表输出在控制台上---------*/
void PrintfUGraph(Graph G)
{ArcNode* p = NULL;for (int i = 0; i < G.vexnum; i++){cout << G.vertices[i].data << ":";p = G.vertices[i].firstarc;while (p != NULL){cout << p->adjvex << " ";p = p->nextarc;}cout << endl;}
}//-----------------------核心代码-----------------------//
void count_chudu(Graph G)
{ int count = 0;ArcNode* p = NULL;for (int i = 0; i < G.vexnum; i++){count = 0;p = G.vertices[i].firstarc;while (p != NULL){count++;p = p->nextarc;}cout << G.vertices[i].data<< "顶点的出度为" << count << "个"<<endl;}
}int count_chudu_zero(Graph G)
{int count = 0;ArcNode* p = NULL;for (int i = 0; i < G.vexnum; i++){p = G.vertices[i].firstarc;if (p == NULL)count++;}return count;
}void count_rudu(Graph G)
{int count = 0;ArcNode* p = NULL;for (int i = 0; i < G.vexnum; i++){count = 0; //clear count every loopfor (int j = 0; j < G.vexnum; j++){p = G.vertices[j].firstarc;while (p != NULL){if (p->adjvex == i)count++;p = p->nextarc;}}cout << G.vertices[i].data << "的入度的数量为:" << count << endl;}
}
//-----------------------核心代码-----------------------//
// 假设不带权有向图采用邻接表G存储,设计实现以下功能的算法。
//(1)求出图中每个顶点的出度。
//(2)求出图中出度为0的顶点数。
//(3) 求出图中每个顶点的入度。
/*
5 6
v1 v2 v3 v4 v5
v1 v2
v1 v4
v3 v4
v2 v3
v3 v5
v2 v5
*/
int main(void)
{Graph G;CreateDG(G);PrintfUGraph(G);cout << "---------------求出图中每个顶点的出度---------------" << endl;count_chudu(G);cout << "---------------求出图中出度为0的顶点数---------------" << endl;cout<<"求出图中出度为0的顶点数:"<<count_chudu_zero(G)<<endl;cout << "---------------求出图中每个顶点的入度---------------" << endl;count_rudu(G);return 0;
}