C++ 图的邻接表转邻接矩阵表示

#include 
#define MaxSize 100

/*
* Created by HarvestWu on 2018/07/20.
*/
using namespace std;
typedef int ElemType;

//邻接矩阵顶点类型
typedef struct VertexType
{
	int no;		//顶点编号
	char info;	
}VertexType;

//图的邻接矩阵类型
typedef struct MGraph
{
	int edges[MaxSize][MaxSize];
	int n, e;	//顶点数、边数
	VertexType vex[MaxSize];//存放结点信息
}MGraph;

//边表
typedef struct ArcNode
{
	int adjvex;                 //该边所指向的结点的位置
	struct ArcNode *nextarc;    //指向下一条边的指针
	int info;                   //
}ArcNode;

//顶点表
typedef struct
{
	char data;                  //顶点信息
	ArcNode *firstarc;          //指向第一条边的指针
}VNode;

//邻接表
typedef struct
{
	VNode adjlist[MaxSize];
	int n, e;                    //顶点数、边数
}AGraph;                        //图的邻接表类型


//创建有向图的邻接表
void createAGraph(AGraph *&AG)
{

	int i, j, k;
	ArcNode *q;
	cout << "输入顶点数、边数:" << endl;
	cin >> AG->n >> AG->e;
	for (i = 0; in; i++)
	{
		AG->adjlist[i].data = i;
		AG->adjlist[i].firstarc = NULL;
	}
	cout << "输入边(vi,vj)的顶点序号i,j:" << endl;
	for (k = 0; ke; ++k)
	{
		cin >> i >> j;
		//头插法
		q = (ArcNode*)malloc(sizeof(ArcNode));
		q->adjvex = j;
		q->nextarc = AG->adjlist[i].firstarc;
		AG->adjlist[i].firstarc = q;

	}
}

//图的邻接表转邻接矩阵表示
void MGraphToAGraph(MGraph &g1, AGraph *g2)
{
	ArcNode *p;
	g1.n = g2->n;
	for (int i = 0; i < g1.n; ++i)
		for (int j = 0; j < g1.n; ++j)
			g1.edges[i][j] = 0;
	for (int i = 0; i < g2->n; ++i)
	{
		p = g2->adjlist[i].firstarc;
		while (p)
		{
			g1.edges[i][p->adjvex-1] = 1;
			p = p->nextarc;
		}
	}
}

//打印图的邻接矩阵
void Visit(MGraph g1)
{
	for (int i = 0; i < g1.n; i++)
	{
		for (int j = 0; j < g1.n; j++)
			cout << g1.edges[i][j] << " ";
		cout << endl;
	}
}

int main()
{
	AGraph *AG;
	MGraph MG;
	AG = (AGraph*)malloc(sizeof(AGraph));
	createAGraph(AG);
	MGraphToAGraph(MG, AG);
	Visit(MG);
	
	return 0;
}

 

你可能感兴趣的:(数据结构(Data,Structure),C/C++)