Function: Creat an undirected graph Args: *G: Pointer to a gragh *ver: An array of vertex value *edge: An array of edges Description: Construct a graph which is stored in the form of an adjacency list */ void creatGraph(Graph* G, VertexType ver[], VertexType edge[][2]) { }
时间: 2024-02-16 18:00:51 浏览: 103
LinuxAPI函数
好的,下面是 `creatGraph` 函数的代码实现:
```c++
void creatGraph(Graph* G, VertexType ver[], VertexType edge[][2]) {
int i, j, k;
ArcNode* p;
for (i = 0; i < MAX_VERTEX_NUM; i++) {
G->adjList[i].firstArc = NULL;
}
G->numVertexes = sizeof(ver) / sizeof(VertexType);
G->numEdges = sizeof(edge) / sizeof(VertexType) / 2;
for (i = 0; i < G->numVertexes; i++) {
G->adjList[i].data = ver[i];
}
for (k = 0; k < G->numEdges; k++) {
i = LocateVertex(G, edge[k][0]);
j = LocateVertex(G, edge[k][1]);
p = (ArcNode*)malloc(sizeof(ArcNode));
p->adjvex = j;
p->nextArc = G->adjList[i].firstArc;
G->adjList[i].firstArc = p;
p = (ArcNode*)malloc(sizeof(ArcNode));
p->adjvex = i;
p->nextArc = G->adjList[j].firstArc;
G->adjList[j].firstArc = p;
}
}
```
其中,`LocateVertex` 函数用于查找顶点在邻接表中的位置,代码如下:
```c++
int LocateVertex(Graph* G, VertexType v) {
int i;
for (i = 0; i < G->numVertexes; i++) {
if (G->adjList[i].data == v) {
return i;
}
}
return -1;
}
```
需要注意的是,在这个函数中,我们假设邻接表中的顶点值不会重复。
阅读全文