__3.3 十字链表—有向图邻接表的优化

#include "pch.h"
#include <iostream>

typedef char VertexType;	//顶点类型
typedef int EdgeType;		//边上的权值类型
#define MAXVEX 100			//最大顶点数
#define myINFINITY 65535	//用65535代表正无穷

//边表节点,用于构建链表
typedef struct EdgeNode {
	int tailVex;			//弧尾的下标
	int headVex;			//弧头的下标
	EdgeNode* tailLink;		//指向 V 指出的下一条边
	EdgeNode* headLink;		//指向指入 V 的下一条边
	EdgeType weight;		//权值
}EdgeNode;

//顶点表节点,用于存储顶点
typedef struct VertexNode {
public:
	VertexNode() : data('\0'), firstIn(nullptr), firstOut(nullptr), id(0), od(0) { }
	VertexType data;		//顶点数据域
	EdgeNode* firstIn;		//边表头指针,指向入度表
	EdgeNode* firstOut;		//边表头指针,指向出度表
	int id, od;				//顶点的入度和出度
}VertexNode, AdjList[MAXVEX];

/*十字链表结构体*/
typedef struct
{
	AdjList adjlist;			//顶点数组
	int numVertexes, numEdges;	//图中顶点数和边数
}CrossAdjList;

//建立有向网的十字链表表示
void CreateCrossAdjList(CrossAdjList* CGL) {
	std::cout << "请依次输入顶点数和边数:";
	std::cin >> CGL->numVertexes >> CGL->numEdges;

	//读入顶点信息,建立顶点表
	for (int i = 0; i < CGL->numVertexes; ++i) {
		std::cout << "请输入第 " << i + 1 << " 个顶点的信息:";
		std::cin >> CGL->adjlist[i].data;
	}

	//读入numEdeges条边,建立边表
	for (int k = 0; k < CGL->numEdges; ++k) {
		int i = 0, j = 0;
		EdgeType w;
		std::cout << "请依次输入边(Vi, Vj)的上标i,下标j和权 W:";
		std::cin >> i >> j >> w;

		EdgeNode* e = new EdgeNode;
		e->tailVex = i;				  //弧起点(弧尾)为 i
		e->headVex = j;				  //弧终点(弧头)为 j
		e->weight = w;				  //权值为 w

		e->tailLink = CGL->adjlist[i].firstOut;	//将 e 的 tailLink 域插入 adjlist[i] 的出度链表,组成正邻接表
		CGL->adjlist[i].firstOut = e;
		e->headLink = CGL->adjlist[j].firstIn;	//将 e 的 headLink 域插入 adjlist[j] 的入度链表,组成逆邻接表
		CGL->adjlist[j].firstIn = e;
		++CGL->adjlist[i].od;			//Vi 的出度增加
		++CGL->adjlist[j].id;			//Vj 的入度增加
	}
}

//打印有向网的十字链表
void ShowCrossAdjList(const CrossAdjList& CGL) {
	std::cout << std::endl << "顶点总数: " << CGL.numVertexes << "  边总数: " << CGL.numEdges << std::endl;

	for (int i = 0; i < CGL.numVertexes; ++i) {
		std::cout << "V" << i << "(" << CGL.adjlist[i].data << ") OD:" << CGL.adjlist[i].od << "  FO";
		auto p = CGL.adjlist[i].firstOut;
		while (p) {
			std::cout << " -> V" << p->headVex << "[" << p->weight << "]";
			p = p->tailLink;
		}

		p = CGL.adjlist[i].firstIn;
		std::cout << "\n      ID:" << CGL.adjlist[i].id << "  FI";
		while (p) {
			std::cout << " -> V" << p->tailVex << "[" << p->weight << "]";
			p = p->headLink;
		}
		std::cout << std::endl << std::endl;
	}
}

int main() {
	CrossAdjList CGL;
	CreateCrossAdjList(&CGL);
	ShowCrossAdjList(CGL);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40843865/article/details/89221887
3.3