数据结构与算法编程题48

有向图的邻接表

#include <iostream>
using namespace std;

#define MVnum 100
typedef string VertexType;

typedef struct ArcNode
{
	int adjvex;
	struct ArcNode* nextarc;
	int weight;
}ArcNode;

typedef struct VNode
{
	VertexType data;
	struct ArcNode* firstarc;
}VNode, VNodeList[MVnum];

typedef struct
{
	VNodeList vertices;
	int vexnum;
	int edgenum;
}Graph;

int locatevex(Graph G, VertexType v)
{
	for (int i = 0; i < G.vexnum; i++)
	{
		if (G.vertices[i].data == v) return i;
	}
	return -1;
}

void CreateDG(Graph& G)
{
	int i = 0, j = 0;
	int k = 0;
	cout << "请输入总顶点数和总边数:";
	cin >> G.vexnum >> G.edgenum;
	cout << "输入顶点:";
	for (i = 0; i < G.vexnum; i++)
	{
		cin >> G.vertices[i].data;
		G.vertices[i].firstarc = NULL;
	}
	for (int k = 0; k < G.edgenum; k++)
	{
		VertexType v1, v2;
		cout << "输入第" << k + 1 << "条边:";
		cin >> v1 >> v2;
		i = locatevex(G, v1);
		j = locatevex(G, v2);
		ArcNode* p1 = (ArcNode*)malloc(sizeof(ArcNode));
		if (p1 == NULL)
		{
			cout << "内存分配失败" << endl;
			exit(0);
		}
		p1->adjvex = j;
		p1->nextarc = G.vertices[i].firstarc;
		G.vertices[i].firstarc = p1;
	}
}

/*--------将邻接表输出在控制台上---------*/
void PrintfUGraph(Graph G) {
	for (int i = 0; i < G.vexnum; i++)
	{
		ArcNode* p = NULL;
		cout << G.vertices[i].data << ":";
		p = G.vertices[i].firstarc;
		while (p != NULL)
		{
			cout << p->adjvex << "  ";
			p = p->nextarc;
		}
		cout << endl;
	}
}
/*
5 6
v1 v2 v3 v4 v5
v1 v2
v1 v4
v3 v4
v2 v3
v3 v5
v2 v5
*/
int main(void)
{
	Graph G;
	CreateDG(G);
	PrintfUGraph(G);
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值