图的邻接多重表存储

萌新小白,请大家多多指教

//图的邻接多重表存储(仅无向图),结构与有向图的十字链表相似
//顶点存放在数组中,每个顶点结构体都带有一个指向依附于该节点的边的指针
//边中存放该边的两个节点索引及其对应的同依附于该节点的一条边的地址
#include<stdio.h>
#include<stdlib.h>
typedef int* Info;
typedef int VertexType;
struct Edge
{
	int mark;//标志位,可用于检测是否遍历过该点或其他用途
	int ivex;//边依附的节点索引
	int jvex;
	struct Edge* ilink;//同依附于i节点的一条边
	struct Edge* jlink;
	Info information;
};
struct Vertex
{
	VertexType data;//顶点信息
	Edge* firstedge;//依附于该顶点的一条边(可以是依附于该节点的任意一条边,以输入顺序为准)
};
struct Graph
{
	Vertex* vlist;//存放顶点的数组首地址
	int vn, en;
};

int Located(Graph& g, int x)
{
	for (int i = 0; i < g.vn; i++)
		if (g.vlist[i].data == x)
			return i;
	return g.vn;
}

void CreateGraph(Graph& g)
{
	printf("Input vertex number , edge number\n");
	scanf("%d%d", &g.vn, &g.en);
	g.vlist = (Vertex*)malloc(g.vn * sizeof(Vertex));
	if (!g.vlist)
	{
		printf("malloc error\n");
		return;
	}
	for (int i = 0; i < g.vn; i++)
	{
		printf("Input vertex\n");
		scanf("%d", &g.vlist[i].data);
		g.vlist[i].firstedge = NULL;
	}
	for (int t = 0; t < g.en; t++)
	{
		int a, b;
		printf("Input vertex of the edge\n");
		scanf("%d%d", &a, &b);
		int i = Located(g, a), j = Located(g, b);
		Edge* temp = (Edge*)malloc(sizeof(Edge));
		*temp = { 0,i,j,g.vlist[i].firstedge,g.vlist[j].firstedge,NULL };
		g.vlist[i].firstedge = g.vlist[j].firstedge = temp;
	}
}

void Print(Graph& g)//检测
{
	for (int i = 0; i < g.vn; i++)
	{
		printf("\nVertex: %d ", g.vlist[i].data);
		Edge* temp = g.vlist[i].firstedge;
		while (temp)
		{
			printf("\nindex of the edge: %d and %d ", temp->ivex, temp->jvex);
			temp = temp->ilink;
		}
	}
}

int main()
{
	Graph g;
	CreateGraph(g);
	Print(g);
}

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值