有向图的十字链表存储;

如题;这是一套完整的可运行的代码;需要读者有一定的基础去阅读;

语言是用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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值