C语言用链表存储读取图的顶点和边的文件信息并打印
时间: 2024-03-03 07:47:14 浏览: 27
好的,我可以为您提供一个简单的C语言示例程序,该程序使用链表存储图的顶点和边的文件信息,并打印出来。以下是代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Edge {
int dest;
int weight;
struct Edge* next;
} Edge;
typedef struct Vertex {
int id;
Edge* edgeList;
} Vertex;
typedef struct Graph {
int numVertices;
Vertex* vertexList;
} Graph;
Graph* createGraph(int numVertices) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->numVertices = numVertices;
graph->vertexList = (Vertex*)malloc(numVertices * sizeof(Vertex));
for (int i = 0; i < numVertices; i++) {
graph->vertexList[i].id = i;
graph->vertexList[i].edgeList = NULL;
}
return graph;
}
void addEdge(Graph* graph, int src, int dest, int weight) {
Edge* newEdge = (Edge*)malloc(sizeof(Edge));
newEdge->dest = dest;
newEdge->weight = weight;
newEdge->next = graph->vertexList[src].edgeList;
graph->vertexList[src].edgeList = newEdge;
}
void printGraph(Graph* graph) {
printf("Number of vertices: %d\n", graph->numVertices);
for (int i = 0; i < graph->numVertices; i++) {
printf("Vertex %d: ", graph->vertexList[i].id);
Edge* edge = graph->vertexList[i].edgeList;
while (edge != NULL) {
printf("(%d, %d) ", edge->dest, edge->weight);
edge = edge->next;
}
printf("\n");
}
}
int main() {
// Read graph from file
FILE* fp = fopen("graph.txt", "r");
if (fp == NULL) {
printf("Failed to open file\n");
return 0;
}
int numVertices, numEdges;
fscanf(fp, "%d %d", &numVertices, &numEdges);
Graph* graph = createGraph(numVertices);
for (int i = 0; i < numEdges; i++) {
int src, dest, weight;
fscanf(fp, "%d %d %d", &src, &dest, &weight);
addEdge(graph, src, dest, weight);
}
fclose(fp);
// Print graph
printGraph(graph);
return 0;
}
```
上述代码中,我们定义了三种数据类型:`Edge`,`Vertex`,和 `Graph`,分别表示边,顶点和图。我们使用 `createGraph` 函数创建了一个具有指定数量顶点的图,使用 `addEdge` 函数将边添加到图中。最后,我们使用 `printGraph` 函数打印图的信息。
假设我们的 `graph.txt` 文件包含以下内容:
```
5 6
0 1 2
0 2 3
1 2 1
1 3 4
2 4 5
3 4 2
```
第一行表示图有 5 个顶点和 6 条边。接下来的每一行表示一条边,由源顶点,目标顶点和权重组成。运行上述代码将输出以下信息:
```
Number of vertices: 5
Vertex 0: (2, 3) (1, 2)
Vertex 1: (3, 4) (2, 1) (0, 2)
Vertex 2: (4, 5) (0, 3) (1, 1)
Vertex 3: (4, 2) (1, 4)
Vertex 4:
```
这表示我们的图有 5 个顶点,顶点 0 与顶点 1 和 2 相连,顶点 1 与顶点 0,2 和 3 相连,以此类推。