十字链表 c++实现

十字链表 c++实现

十字链表面向有向图的另一种链表存储结构,包含了领接表和逆领接表的特性,可以快速的访问出弧和入弧,得到出度和入度。同弧头是顶点的入度链表,同弧尾是顶点的出度链表

#include<iostream>
using namespace std;
const int maxNum = 100;
typedef struct arcNode {    //弧结点类型
	int tail;				//弧尾下标
	int head;				//弧头下标
	struct arcNode*hlink;	//指针,指向同弧头的弧
	struct arcNode*tlink;	//指针,指向同弧尾的弧
}arcNode;
typedef struct vexNode
{
	char data;				//指点数据
	arcNode *firstIn;		//指针,指向第一个入弧
	arcNode *firstout;		//指针,指向第一个出弧
};
typedef struct {
	vexNode vex[maxNum];
	int vexnum, edgenum;	//顶点数量,边数量
}OLGraph;
OLGraph g;
int LocateVex(char c)
{
	for (int i = 0; i < g.vexnum; i++)
	{
		if (g.vex[i].data == c)
		{
			return i;
		}
	}
	return -1;
}
void insertedge(char a, char b)
{
	int ai = LocateVex(a);
	int bi = LocateVex(b);
	arcNode* an = new arcNode;						//生成一条新弧
	an->tlink = g.vex[ai].firstout;		
	an->head = bi;						//由ai->bi
	an->tail = ai;
	g.vex[ai].firstout = an;			//顶点第一个出弧更新,头插入
	an->hlink = NULL;
	if (g.vex[bi].firstIn == NULL)
	{
		g.vex[bi].firstIn = an;
	}
	else 
	{
		arcNode* curArc = g.vex[bi].firstIn;		//找到最后一个入弧,尾插入
		while (curArc->hlink != NULL)
		{
			curArc = curArc->hlink;
		}
		curArc->hlink = an;
	}
}
void CreateOLGraph() {
	cout << "请输入顶点数量和边数:" << endl;
	cin >> g.vexnum >> g.edgenum;
	cout << "输入对应的顶点:" << endl;
	for (int i = 0; i < g.vexnum; i++)
	{
		cin >> g.vex[i].data;
		g.vex[i].firstIn = NULL; 
		g.vex[i].firstout = NULL;
	}
	cout << "输入要插入的边" << endl;
	int m = g.edgenum;
	while (m > 0)
	{
		char a, b;
		cin >> a >> b;
		insertedge(a, b);
		m--;
	}
}
void GetOLVexDu() {			//获得十字链表中某一个点的入度和出度
	for (int i = 0; i < g.vexnum; i++)
	{
		vexNode n = g.vex[i];
		cout << n.data << "的出度有" << " : ";
		arcNode* outArc = n.firstout;
		while (outArc != NULL)
		{
			cout << outArc->head << " ";
			outArc = outArc->tlink;
		}
		cout << endl;
		cout << n.data << "的入度有" << " : ";
		arcNode* inArc = n.firstIn;
		while (inArc != NULL)
		{
			cout << inArc->tail << " ";
			inArc = inArc->hlink;
		}
		cout << endl;
	}
}
int main()
{
	CreateOLGraph();
	GetOLVexDu();
	return 0;
}

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JustEasyCode

谢谢您

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值