数据结构-图-C语言-邻接表
#include <stdio.h>
#include <stdlib.h>
#define Max 100
typedef int Vertex;
typedef int WeightType;
/**
*
* @author Caedios
* @attr v1 顶点v1,即有向边v1->v2
* @attr v2 顶点v2,即有向边v1->v2
* @attr weight 边的权重
*
*/
struct ENode {
Vertex v1, v2;
WeightType weight;
};
typedef struct ENode * pENode;
/**
*
* @author Caedios
* @attr subNum 邻接点下标
* @attr weight 边权重
* @attr pVNode 指向下个邻接点
*
*/
struct VNode {
Vertex subNum;
WeightType weight;
pVNode nextVNode;
};
typedef struct VNode * pVNode;
/**
*
* @author Caedios
* @attr headVNode 邻接表的头顶点指针
*
*/
struct HeadVNode {
pVNode headVNode;
};
typedef struct HeadVNode AdjList[Max];
/**
*
* @author Caedios
* @attr numVertex 顶点数
* @attr numEdge 边数
* @attr adjList 邻接表
*
*/
struct Graph {
int numVertex;
int numEdge;
AdjList adjList;
};
typedef struct Graph * pGraph;
pGraph createGraph(int vertexNum) {
Vertex v;
pGraph graph;
graph = (pGraph)malloc(sizeof(struct Graph));
graph->numVertex = vertexNum;
graph->numEdge = 0;
for (v = 0; v < graph->numVertex; v++)
graph->adjList[v].headVNode = NULL;
return graph;
}
pGraph insertGraph(pGraph graph,pENode edge) {
pVNode newNode = (pVNode)malloc(sizeof(struct VNode));
newNode->subNum = edge->v2;
newNode->weight = edge->weight;
newNode->nextVNode = graph->adjList[edge->v1].headVNode;
graph->adjList[edge->v1].headVNode = newNode;
return graph;
}
pGraph buildGraph() {
pGraph graph;
pENode edge;
int vertexNum;
scanf("%d", &vertexNum);
graph = createGraph(vertexNum);
scanf("%d", graph->numEdge);
if (graph->numEdge > 0) {
edge = (pENode)malloc(sizeof(struct ENode));
for (int i = 0; i < graph->numEdge; i++) {
scanf("%d %d %d", edge->v1, edge->v2, edge->weight);
insertGraph(graph, edge);
}
}
return graph;
}
来源:CSDN
作者:CaediosViolet
链接:https://blog.csdn.net/qq_40925226/article/details/83513863