# 用邻接表实现图的构建

#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;

//邻接点定义
WeigthType weight; //边的权重

//表头节点定义
typedef struct VNode {
DataType Data; //可不用

// 图结点的定义
typedef struct GNode {
int Nv;     /* 顶点数 */
int Ne;     /* 边数   */
}*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)
{

newNode->weight = E->weigth;
newNode->Next = Graph->G[E->v1].FirstEdge;
Graph->G[E->v1].FirstEdge = newNode;

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();
}


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