图的基本操作
邻接矩阵
#include<iostream>
using namespace std;
#define MaxVertexNum 100
#define INFINITY 65532
typedef int Vertex;
typedef int WeightType;
typedef char DataType;
typedef struct GNode *PtrToGNode;
//图结点的定义
struct GNode
{
int Nv;
int Ne;
WeightType G[MaxVertexNum][MaxVertexNum];
DataType Data[MaxVertexNum];
};
typedef PtrToGNode MGraph;
//边的定义
typedef struct ENode *PtrToENode;
struct ENode
{
Vertex v1, v2;
WeightType weight;
};
typedef PtrToENode Edge;
MGraph CreateGraph(int vertexnum)
{
Vertex v, w;
MGraph Graph;
Graph = (MGraph)malloc(sizeof(struct GNode));
Graph->Nv = vertexnum;
Graph->Ne = 0;
for (v = 0; v < Graph->Nv; v++)
{
for (w = 0; w < Graph->Nv; w++)
{
Graph->G[v][w] = INFINITY;
}
}
return Graph;
}
void InsertEdge(MGraph Graph, Edge E)
{
Graph->G[E->v1][E->v2] = E->weight;
Graph->G[E->v2][E->v1] = E->weight;
}
MGraph BuildGraph()
{
MGraph Graph;
Edge E;
Vertex V;
int Nv;
cin >> Nv;//读入顶点个数;
Graph = CreateGraph(Nv);
cin >> Graph->Ne;
if (Graph->Ne) E = (Edge)malloc(sizeof(struct ENode));
for (int i = 0; i < Graph->Ne; i++)
{
cin >> E->v1 >> E->v2 >> E->weight;
InsertEdge(Graph, E);
}
//如果顶点有数据,读入数据
for (int v = 0; v < Graph->Nv; v++)
{
cin >> Graph->Data[v];
}
return Graph;
}
邻接表
#include<iostream>
using namespace std;
#define MaxVertexNum 100
typedef int Vertex;
typedef int WeightType;
typedef char DataType;
//边的定义
typedef struct ENode *PtrToENode;
struct ENode
{
Vertex v1, v2;
WeightType Weight;
};
typedef PtrToENode Edge;
//邻接点的定义
typedef struct AdjVNode * PtrToAdjVNode;
struct AdjVNode
{
Vertex AdjV;
WeightType Weight;
PtrToAdjVNode Next;
};
//顶点表头结点的定义
typedef struct Vnode
{
PtrToAdjVNode FirstEdge;//边表头指针
DataType Data;//存顶点的数据
}AdjList[MaxVertexNum];//AdjList是邻接表类型
//图结点的定义
typedef struct GNode *PtrToGNode;
struct GNode
{
int Nv;
int Ne;
AdjList G;//邻接表
};
typedef PtrToGNode LGraph;
LGraph CreateGraph(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)//插入边<v1,v2>
{
PtrToAdjVNode NewNode;
NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));//为v2建立新的邻接点
NewNode->AdjV = E->v2;
NewNode->Weight = E->Weight;
NewNode->Next = Graph->G[E->v1].FirstEdge;
Graph->G[E->v1].FirstEdge=NewNode;
//若为无向图,还要插入边<v2,v1>
NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
NewNode->AdjV = E->v1;
NewNode->Weight = E->Weight;
NewNode->Next = Graph->G[E->v2].FirstEdge;
Graph->G[E->v2].FirstEdge = NewNode;
}
LGraph BuildGraph()
{
LGraph Graph;
Edge E;
Vertex v;
int Nv;
cin >> Nv;
Graph = CreateGraph(Nv);
cin >> Graph->Ne;
if (Graph->Ne)
{
E = (Edge)malloc(sizeof(struct ENode));
for (int i = 0; i < Graph->Ne; i++)
{
cin >> E->v1 >> E->v2 >> E->Weight;
InsertEdge(Graph, E);
}
}
for (v = 0; v < Graph->Nv; v++)
{
cin >> Graph->G[v].Data;
}
return Graph;
}
来源:CSDN
作者:寻余
链接:https://blog.csdn.net/weixin_43725617/article/details/104104390