用邻接表实现图的构建

#include<stdio.h>
#include<stdlib.h>

#define MaxVertexNum 100

typedef int Vertex; //顶点下标
typedef int WeigthType; //边的权值
typedef int DataType; //顶点的数据类型

//边的定义
typedef struct ENode {
	Vertex v1, v2;
	WeigthType weigth;
}*PtrToENode;
typedef PtrToENode Edge;

//邻接点定义
typedef struct AdjVNode {
	Vertex AdjV; //邻接点的下标
	WeigthType weight; //边的权重
	struct AdjVNode* Next; //下一个邻接点
}*PtrToAdjVNode;

//表头节点定义
typedef struct VNode {
	PtrToAdjVNode FirstEdge;
	DataType Data; //可不用
}AdjList[MaxVertexNum];

// 图结点的定义 
 typedef struct GNode {
	int Nv;     /* 顶点数 */
	int Ne;     /* 边数   */
	AdjList G;  /* 邻接表 */
}*PtrToGNode;
typedef PtrToGNode LGraph; 

// 初始化没有边的图
LGraph CreatGraph(int VertexNum)
{ 
    Vertex V;
    LGraph Graph;

    Graph = (LGraph)malloc(sizeof(struct GNode)); 
    Graph->Nv = VertexNum;
    Graph->Ne = 0;
    
    for (V = 0; V < Graph->Nv; V++)
        Graph->G[V].FirstEdge = NULL;

    return Graph;
}

//插入一条边
void InsertEdge(LGraph Graph, Edge E)
{
	PtrToAdjVNode newNode;

	newNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
	newNode->AdjV = E->v2;
	newNode->weight = E->weigth;
	newNode->Next = Graph->G[E->v1].FirstEdge;
	Graph->G[E->v1].FirstEdge = newNode;

	newNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
	newNode->AdjV = E->v1;
	newNode->weight = E->weigth;
	newNode->Next = Graph->G[E->v2].FirstEdge;
	Graph->G[E->v2].FirstEdge = newNode;
}

//构建一个图
LGraph BuildGraph()
{
	int Nv, i;
	Vertex V;
	Edge E;
	LGraph Graph;

	printf_s("请输入插入节点的个数\n");
	scanf_s("%d", &Nv);

	Graph = CreatGraph(Nv);

	printf_s("请输入插入边的个数\n");
	scanf_s("%d", &(Graph->Ne));
	if (Graph->Ne != 0)
	{
		E = (Edge)malloc(sizeof(struct ENode));
		if (!E)
		{
			printf("E生成失败");
			exit(-1);
			return NULL;
		}
		for (i = 0; i < Graph->Ne; i++)
		{
			printf("请输入第%d条边:  V1,V2,权重\n", i);
			scanf_s("%d %d %d", &(E->v1), &(E->v2), &(E->weigth));
			InsertEdge(Graph, E);
		}
	}

	for (V = 0; V < Graph->Nv; V++)
	{
		printf("请输入第%d个顶点的数据\n", V);
		scanf_s("%d", &(Graph->G[V].Data));
	}

	return Graph;
}

void main()
{
	printf("无向图\n");
	LGraph Graph;
	Graph = BuildGraph();
}
发布了29 篇原创文章 · 获赞 11 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览