十字链表

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

C代码

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
#define MaxVertexNum 100  // 图中顶点数目的最大值
typedef char VertexType;

// 边表结点
typedef struct ArcNode{
	int tailvex;  // 这条弧的弧尾(起点)所在顶点下标
	int headvex;  // 这条弧的弧头(终点)所在顶点下标
	struct ArcNode *hlink;  // 指向弧头(终点)相同的下一条边
	struct ArcNode *tlink;  // 指向弧尾(起点)相同的下一条边
}ArcNode;
//顶点结点
typedef struct VNode{
	VertexType data;  // 图中顶点的数据
	ArcNode *firstin;  // 该顶点的入边表的头指针
	ArcNode *firstout;  // 该顶点的出边表的头指针
}VNode;
// 十字链表存储的图类型
typedef struct{
	VNode xlist[MaxVertexNum];  //顶点用顺序存储(数组)
	int vexnum, arcnum;  //图的顶点数和弧数
}GLGraph;

int LocalBow(char data, GLGraph *g){  // 查询顶点的位置
	int i;
	for (int i = 0; i < g->arcnum; ++i){
		if (g->xlist[i].data == data){
			return i;
		}
	}
	return 0;
}

// 创建十字链表
void Create(GLGraph *g){
	char start;
	char end;
	int i;
	int hw;
	int ht;
	cout << "请输入图的顶点和弧的数量: ";
	cin >> g->arcnum >> g->vexnum;
	for (i = 0; i < g->arcnum; ++i){
		cout << "请输入第" << i + 1 << "个顶点的值:";
		cin >> g->xlist[i].data;
		g->xlist[i].firstin = NULL;  // 初始化指针,否自会成为野指针
		g->xlist[i].firstout = NULL;
	}

	for (i = 0; i < g->vexnum; ++i){
		cout << "请输入<vi,vj>:";
		cin >> start >> end;  // 接收从start ----> end
		ArcNode *node = (ArcNode *)malloc(sizeof(ArcNode));
		node->headvex = start;  
		node->tailvex = end;  
		hw = LocalBow(start, g);  // 找到字符在数组中的下标,弧尾
		ht = LocalBow(end, g);  // 弧头  start -------> end
		node->hlink = g->xlist[ht].firstin;  // 头插法,弧头指针指向弧头的入边表
		node->tlink = g->xlist[hw].firstout;  // 头插法,弧尾指针指向弧尾的出边表
		g->xlist[ht].firstin = node;
		g->xlist[hw].firstout = node;
	}
}

int main()
{
	GLGraph G;
	ArcNode *t;
	Create(&G);
	int i;
	for (i = 0; i<G.vexnum; i++)
	{
		printf("%c顶点出度情况为:\n", G.xlist[i].data);
		t = G.xlist[i].firstout;
		if (!t)	printf("无");
		while (t)
		{
			printf("%c->%c ", t->headvex, t->tailvex);
			t = t->tlink;
		}
		printf("\n");
		t = G.xlist[i].firstin;
		printf("%c顶点入度情况为:\n", G.xlist[i].data);
		if (!t)		printf("无");
		while (t)
		{
			printf("%c->%c ", t->headvex, t->tailvex);
			t = t->hlink;
		}
		printf("\n");
	}
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值