-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgraph.c
101 lines (82 loc) · 1.7 KB
/
graph.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <stdio.h>
#include <stdlib.h>
/** 邻接表(Adjacency List)可表示图,在C语言使用结构体和链表来实现 */
// 定义节点结构体
struct Node
{
int vertex;
struct Node *next;
};
// 定义图结构体
struct Graph
{
int numVertices;
struct Node **adjLists;
};
// 创建节点
struct Node *createNode(int v)
{
struct Node *newNode = malloc(sizeof(struct Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// 创建图
struct Graph *createGraph(int vertices)
{
struct Graph *graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct Node *));
for (int i = 0; i < vertices; i++)
{
graph->adjLists[i] = NULL;
}
return graph;
}
// 添加边
void addEdge(struct Graph *graph, int src, int dest)
{
struct Node *newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
// 打印图
void printGraph(struct Graph *graph)
{
for (int v = 0; v < graph->numVertices; v++)
{
struct Node *temp = graph->adjLists[v];
printf("\n Vertex %d\n: ", v);
while (temp)
{
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}
int main()
{
struct Graph *graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);
printGraph(graph);
return 0;
}
/**
jarry@jarrys-MacBook-Pro graph % gcc graph.c
jarry@jarrys-MacBook-Pro graph % ./a.out
Vertex 0
: 2 -> 1 ->
Vertex 1
: 2 -> 0 ->
Vertex 2
: 3 -> 1 -> 0 ->
Vertex 3
: 2 ->
*/