include <stdio.h>
include <stdlib.h>
// 定义邻接表的边节点
typedef struct EdgeNode {
int adjVertex;
struct EdgeNode *next;
} EdgeNode;
// 定义邻接表的顶点节点
typedef struct VertexNode {
int data;
EdgeNode *firstEdge;
} VertexNode;
// 定义邻接表
typedef struct {
VertexNode *adjList;
int numVertices;
int numEdges;
} GraphAdjList;
// 创建图
GraphAdjList* createGraph(int numVertices) {
GraphAdjList graph = (GraphAdjList)malloc(sizeof(GraphAdjList));
graph->numVertices = numVertices;
graph->numEdges = 0;
graph->adjList = (VertexNode*)malloc(numVertices * sizeof(VertexNode));
for (int i = 0; i < numVertices; i++) {
graph->adjList[i].data = i;
graph->adjList[i].firstEdge = NULL;
}
return graph;
}
// 添加边
void addEdge(GraphAdjList *graph, int src, int dest) {
EdgeNode newNode = (EdgeNode)malloc(sizeof(EdgeNode));
newNode->adjVertex = dest;
newNode->next = graph->adjList[src].firstEdge;
graph->adjList[src].firstEdge = newNode;
// 无向图需要对称添加
newNode = (EdgeNode*)malloc(sizeof(EdgeNode));
newNode->adjVertex = src;
newNode->next = graph->adjList[dest].firstEdge;
graph->adjList[dest].firstEdge = newNode;graph->numEdges++;
}
// 打印图
void printGraph(GraphAdjList *graph) {
for (int i = 0; i < graph->numVertices; i++) {
printf("顶点 %d 的邻接表: ", graph->adjList[i].data);
EdgeNode *node = graph->adjList[i].firstEdge;
while (node) {
printf("%d -> ", node->adjVertex);
node = node->next;
}
printf("NULL\n");
}
}
// 释放图的内存
void freeGraph(GraphAdjList *graph) {
for (int i = 0; i < graph->numVertices; i++) {
EdgeNode *node = graph->adjList[i].firstEdge;
EdgeNode *nextNode;
while (node) {
nextNode = node->next;
free(node);
node = nextNode;
}
}
free(graph->adjList);
free(graph);
}