如题;这是一套完整的可运行的代码;需要读者有一定的基础去阅读;
语言是用C语言实现;在C++环境中编写;在C++中可直接运行;在C语言中需要改部分头文件和输出语句;
头文件;这要是代码的声明部分;
# ifndef _OLGRAPH_
# define _OLGRAPH_
//包含相关的库;
# include <iostream>
using namespace std;
//定义相关的宏;
# define MaxVertexNum 256
//定义标识边上信息的类型;
typedef int InfoType;
//定义顶点储存的数据的类型;
typedef char VertexType;
//定义边节点类型;
typedef struct EdgeNode
{
int tailvertex;
struct EdgeNode * taillink;
int headvertex;
struct EdgeNode * headlink;
InfoType info;
}EdgeNode;
//定义顶点节点类型;
typedef struct VertexNode
{
VertexType vertex;
EdgeNode * firstin;
EdgeNode * firstout;
}VertexNode;
//定义图的类型;
typedef struct
{
VertexNode xlist[MaxVertexNum];
int vertexNum;
int edgeNum;
}OLGraph, * POLGraph;
POLGraph CreateGraph(void);
# endif
实现文件;主要是代码的实现;
# include "OLGraph.h"
POLGraph CreateGraph(void)
{
POLGraph g = (POLGraph)malloc(sizeof(OLGraph));
if (NULL != g)
{
memset(g, 0, sizeof(OLGraph));
g->vertexNum = 0;
g->edgeNum = 0;
//输入定点数和边数;
cout << "Please input VertexNum and EdgeNum: " << endl;
cin >> g->vertexNum >> g->edgeNum;
//初始化顶点表;
for (int i = 0; i < g->vertexNum; i++)
{
cout << "Please input element value: " << endl;
cin >> g->xlist[i].vertex;
g->xlist[i].firstin = NULL;
g->xlist[i].firstout = NULL;
}
//连接边;
int i = 0;
int j = 0;
EdgeNode * p = NULL;
for (int k = 0; k < g->edgeNum; k++)
{
//输入边的两个端点;
cout << "Please input edge two index; " << endl;
cin >> i >> j;
//申请边节点;
p = (EdgeNode *)malloc(sizeof(EdgeNode));
//检查边节点内存分配情况;
if (NULL == p)
{
cout << "EdgeNode allocate error! " << endl;
system("pause");
exit(0);
}
//边节点序号赋值;
p->tailvertex = i;
p->headvertex = j;
//连接弧尾相同的下一节点;
p->taillink = g->xlist[i].firstout;
g->xlist[i].firstout = p;
//连接弧头相同的下一节点;
p->headlink = g->xlist[j].firstin;
g->xlist[j].firstin = p;
//边上相关信息;
p->info = 0;
}
return g;
}
else
{
//内存分配时失败;
cout << "Memory allocate error! " << endl;
system("pause");
exit(0);
}
}
Main函数;
# include "OLGraph.h"
typedef struct
{
int outdeg;
int indeg;
}Degree;
int main(int argc, char ** argv)
{
POLGraph g = CreateGraph();
Degree degree[10] = { 0 };
EdgeNode * p = NULL;
for (int i = 0; i < g->vertexNum; i++)
{
p = g->xlist[i].firstout;
while (NULL != p)
{
degree[i].outdeg += 1;
p = p->taillink;
}
p = g->xlist[i].firstin;
while (NULL != p)
{
degree[i].indeg += 1;
p = p->headlink;
}
}
for (int i = 0; i < g->vertexNum; i++)
{
cout << degree[i].indeg << ", " << degree[i].outdeg << endl;
}
system("pause");
return 0;
}