邻接表创建无向表(C++ 代码)

邻接表创建无向表(C++ 代码)_第1张图片

 

#include//邻接表创建无向表
#define MVNum 100
using namespace std;
typedef char VerTexType;
typedef struct Arcnode//边节点
{
	int adjvex;//该边所指向的顶点的位置
	struct Arcnode* nextarc;//指向下一条边的指针
}Arcnode;
typedef struct vnode//顶点节点
{
	VerTexType data;//顶点信息
	Arcnode* firstarc;//指向第一条依附该顶点的边的指针
}Vnode,AdjList[MVNum];
typedef struct//图
{
	AdjList vertices;//头顶点
	int vexnum, arcnum;//图当前顶点数和边数
}ALGraph;
int LocateVex(ALGraph G, VerTexType u)
{
	for (int i = 0; i < G.vexnum; i++)
		if (u == G.vertices[i].data) return i;
	return -1;
}
bool CreateUDG(ALGraph& G)
{
	cin >> G.vexnum >> G.arcnum;//输入总顶点数,总边数
	for (int i = 0; i < G.vexnum; i++)//输入各点,构造表头结点表
	{
		cin >> G.vertices[i].data;//输入顶点值
		G.vertices[i].firstarc = NULL;//初始化表头节点指针域
	}
	VerTexType v1, v2;
	for (int k = 0; k < G.arcnum; k++)
	{
		cin >> v1 >> v2;//输入边相邻节点
		int i = LocateVex(G, v1);
		int j = LocateVex(G, v2);//确定v1,v2位置
		Arcnode* p1,*p2;
		p1 = new Arcnode;//生成一个新的边节点
		p1->adjvex = j;//邻节点序号为j
		p1->nextarc = G.vertices[i].firstarc;
		G.vertices[i].firstarc = p1;//将新节点插入顶点vi的边表头部
		p2 = new Arcnode;
		p2->adjvex = i;//邻接点序号为i
		p2->nextarc = G.vertices[j].firstarc;
		G.vertices[j].firstarc = p2;//将新节点插入顶点vj的表头部
	}
	return 1;
}
bool Print(ALGraph& G)
{
	cout << "邻接表:" << endl;
	for (int i = 0; i < G.vexnum; i++)
	{
		cout << G.vertices[i].data << " ";
		while (G.vertices[i].firstarc != NULL)
		{
			cout << G.vertices[G.vertices[i].firstarc->adjvex].data << " ";
			G.vertices[i].firstarc = G.vertices[i].firstarc->nextarc;
		}
		cout << endl;
	}
	return 1;
}
int main()
{
	ALGraph G;
	CreateUDG(G);
	Print(G);
}

 邻接表创建无向表(C++ 代码)_第2张图片

 

你可能感兴趣的:(c++,图论,深度优先)