有向图十字链表表示及各顶点出入度计算

#include<iostream>
#define MAX_VERTEX_NUM 50
using namespace std;

//定义顶点信息数据类型
typedef char VertexData;

//定义图的种类
typedef enum{DG,UDG} GraphKind;

//定义弧结点
typedef struct ArcNode
{
	int tailvex,headvex;		//定义弧结点的弧头,弧尾在图中的位置
	ArcNode *tlink,*hlink;
}ArcNode;

//定义顶点
typedef struct VertexNode
{
	VertexData data;
	ArcNode *firstin,*firstout;
}VertexNode;

//定义有向图的十字链表
typedef struct OrthList
{
	VertexNode Vertex[MAX_VERTEX_NUM];
	int vertexNum,arcNum;		//定义顶点数,弧数
	GraphKind kind;
}OrthList;

void CreateOrthList(OrthList *orthList)
{	
	ArcNode *q=NULL;
	int s,d;					//定义弧结点的起始,目的位置
	cout<<"输入有向图的顶点数(vNum),边数(eNum)\n";
	cin>>orthList->vertexNum>>orthList->arcNum;
	orthList->kind=DG;
	//初始化十字链表顶点信息
	for(int i=1;i<=orthList->vertexNum;i++)
	{
		cout<<"输入第"<<i<<"个顶点的信息\n";
		cin>>orthList->Vertex[i].data;
		orthList->Vertex[i].firstin=NULL;
		orthList->Vertex[i].firstout=NULL;
	}
	for(i=1;i<=orthList->arcNum;i++)
	{	
		q=(ArcNode *)malloc(sizeof(ArcNode));
		cout<<"输入第"<<i<<"条边的起始(s)目的位置(d)\n";
		cin>>s>>d;
		q->tailvex=s;q->headvex=d;
		q->tlink=orthList->Vertex[s].firstout;
		orthList->Vertex[s].firstout=q;
		q->hlink=orthList->Vertex[d].firstin;
		orthList->Vertex[d].firstin=q;
	}

}

//求每个顶点的出度与入度
void GetDegree(OrthList *orthList)
{	
	ArcNode *q=NULL;
	int outDegree,inDegree;             
	for(int i=1;i<=orthList->vertexNum;i++)
	{	
		outDegree=0;inDegree=0;
		//计算顶点Vertex[i]的出度
		q=orthList->Vertex[i].firstout;
		while(q!=NULL)
		{
			outDegree++;
			q=q->tlink;
		}
		//	//计算顶点Vertex[i]的入度
		q=orthList->Vertex[i].firstin;
		while(q!=NULL)
		{
			inDegree++;
			q=q->hlink;
		}
		cout<<"顶点"<<orthList->Vertex[i].data<<"的出度为"<<outDegree<<endl;
		cout<<"顶点"<<orthList->Vertex[i].data<<"的入度为"<<inDegree<<endl<<endl;
	}
}



int main()
{	
	OrthList *orthList=(OrthList *)malloc(sizeof(OrthList));
	CreateOrthList(orthList);
	GetDegree(orthList);
	return 0;
}
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值