图的创建——十字链表

邻接表 + 逆邻接表 = 十字链表 (十字链表把邻接表和逆邻接表整合在一起)

邻接表:计算出度容易,但计算入度就需要遍历全图,故衍生了十字链表。

#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;

const int VERTEX_NUM = 20;			// 最大允许的顶点数 

// 边表的结点(单链表) 
class EdgeNode {
public:
	int beg;
	int end;
	int weight;
	EdgeNode *headlink;
	EdgeNode *taillink;
}; 

// 顶点表的结点 
class VertexNode {
public:
	int vertexData;
	EdgeNode *firstin;
	EdgeNode *firstout;
};

// 图的结构 
class Graph {
public:
	VertexNode vertex[VERTEX_NUM];		
	int vertexNum;			// 当前图的顶点数 
	int edgeNum;			// 当前图的边数 
};

void createGraph(Graph &G)
{
	cout << "请输入无向图的顶点数和边数:";
	cin >> G.vertexNum >> G.edgeNum;
	// 读入顶点信息,建立顶点表 
	for (int i = 0; i != G.vertexNum; ++i) {
		cout << "请输入第" << i + 1 << "个顶点的序号:";
		cin >> G.vertex[i].vertexData;
		G.vertex[i].firstin = NULL;		// 将边表置位空表 
		G.vertex[i].firstout = NULL;
	}
	// 建立边表 
	for (int k = 0; k != G.edgeNum; ++k) {
		cout << "请输入边(vi, vj)的顶点i、j及权重w:";
		int i, j, w;
		cin >> i >> j >> w;
		EdgeNode *q = (EdgeNode*)malloc(sizeof(EdgeNode));		// 生成边表结点,下同单链表的头插入 
		q->beg = i;
		q->end = j;
		q = G.vertex[i].firstout;
		G.vertex[i].firstout = q;
		q = G.vertex[j].firstin;					// 逆邻接表的思想
		G.vertex[j].firstin = q;					 
		EdgeNode *s = (EdgeNode*)malloc(sizeof(EdgeNode));
		s->beg = j;
		s->end = i;
		s = G.vertex[j].firstout;
		G.vertex[j].firstout = s;
		s = G.vertex[i].firstin;					// 逆邻接表的思想
		G.vertex[i].firstin = s;
	}
}

int main()
{
	Graph G;
	createGraph(G);
}

  

原文地址:https://www.cnblogs.com/xzxl/p/8645401.html