采用邻接表法创建无向图,利用数组
时间: 2023-12-20 17:53:00 浏览: 46
实现。邻接表法是一种图的表示方法,其中每个顶点都与一个链表相关联,该链表列出了与该顶点直接相连的所有其他顶点。
具体实现步骤如下:
1. 声明一个结构体类型来表示图中的每个顶点。该结构体应包括一个顶点的值和一个指向该顶点的邻接链表的指针。
2. 声明一个结构体类型来表示邻接链表中的每个节点。该结构体应包括一个顶点的值和一个指向下一个节点的指针。
3. 声明一个数组来存储图中的所有顶点。数组中的每个元素都是一个指向该顶点的结构体指针。
4. 对于每个顶点,创建一个邻接链表,并将其指针存储在该顶点的结构体中。链表中的节点对应于该顶点的所有直接相连的顶点。
5. 可以通过遍历每个顶点的邻接链表来访问该顶点的所有相邻顶点。
下面是一个示例代码,用于创建一个包含5个顶点的无向图:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int vertex;
struct node* next;
};
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
struct Graph {
int numVertices;
struct node** adjLists;
};
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
int i;
for (i = 0; i < vertices; i++)
graph->adjLists[i] = NULL;
return graph;
}
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Add edge from dest to src
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
void printGraph(struct Graph* graph) {
int v;
for (v = 0; v < graph->numVertices; v++) {
struct node* temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);
while (temp) {
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}
int main() {
struct Graph* graph = createGraph(5);
addEdge(graph, 0, 1);
addEdge(graph, 0, 4);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);
printGraph(graph);
return 0;
}
```
输出结果如下:
```
Adjacency list of vertex 0
4 -> 1 ->
Adjacency list of vertex 1
4 -> 3 -> 2 -> 0 ->
Adjacency list of vertex 2
3 -> 1 ->
Adjacency list of vertex 3
4 -> 2 -> 1 ->
Adjacency list of vertex 4
3 -> 1 -> 0 ->
```
可以看到,每个顶点的邻接链表都被正确地创建和连接。