用数组存储和创建图结构

问题:定义结构体要分配空间,这个不知为什么?

有很长时间没写数据结构了,忙,也不知忙什么。。。下面创建的是无向图。主要是记得图的结构体的定义,我刚开始没想起来,查了资料才弄明白的。

代码:

#include <iostream>
#include <cstdlib>
using namespace std;
#define MAXVEX 20
typedef struct map
{
	char vex[MAXVEX];
	int arrMap[MAXVEX][MAXVEX];
	int numvexs,numedges;
}mapNode;

int getPos(mapNode *g,char v)    //返回顶点的位置
{
	int i=0;
	for(i=0;i<g->numvexs;i++)
	{
		if(g->vex[i]==v)
		{
			break;
		}
	}
	if(i>=g->numvexs)
		return -1;
	return i;
}

void  createGraph(mapNode* &g)
{
	char p,q;
	int m,n;
	cout<<"please input the nums of the vexs and edges:";
	cin>>g->numvexs;
	cin>>g->numedges;
	getchar();
	cout<<"input the infor of the vexs:"<<endl;
	for(int i=0;i<g->numvexs;i++)
	{
		cin>>g->vex[i];
	}

	for(int k=0;k<g->numvexs;k++)            //初始化图矩阵
	{
		for(int r=0;r<g->numvexs;r++)
		{
			g->arrMap[k][r]=0;
		}
	}

	for(int j=0;j<g->numedges;j++)
	{
		cout<<"please input two vexs:";
		cin>>p>>q;
		m=getPos(g,p);
		n=getPos(g,q);
		if(m==-1||n==-1)
		{
			cout<<"输入错误"<<endl;
			return;
		}
		else
		{
			g->arrMap[m][n]=1;
			g->arrMap[n][m]=1;
		}
	}
}

void playMap(mapNode *g)
{
	for(int i=0;i<g->numvexs;i++)
	{
		for(int j=0;j<g->numvexs;j++)
		{
			cout<<g->arrMap[i][j]<<"  ";
		}
		cout<<endl;
	}
	cout<<endl;
}

int main()
{
	mapNode *mn=NULL;
	mn=(mapNode *)malloc(sizeof(struct map));
	if(!mn)
		return -1;
	cout<<"创建图:"<<endl;
	createGraph(mn);
	cout<<"输出图:"<<endl;
	playMap(mn);
	return 0;
}

 运行结果:

原文地址:https://www.cnblogs.com/xshang/p/3069204.html