-
Notifications
You must be signed in to change notification settings - Fork 253
/
Implement_of_Graph
81 lines (60 loc) · 1.4 KB
/
Implement_of_Graph
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
#include <stdio.h>
#include <stdlib.h>
#define N 6
struct Graph
{
struct Node* head[N];
};
struct Node
{
int dest;
struct Node* next;
};
struct Edge {
int src, dest;
};
struct Graph* createGraph(struct Edge edges[], int n)
{
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
for (int i = 0; i < N; i++) {
graph->head[i] = NULL;
}
for (int i = 0; i < n; i++)
{
int src = edges[i].src;
int dest = edges[i].dest;
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->dest = dest;
newNode->next = graph->head[src];
graph->head[src] = newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->dest = src;
newNode->next = graph->head[dest];
graph->head[dest] = newNode;
}
return graph;
}
void printGraph(struct Graph* graph)
{
for (int i = 0; i < N; i++)
{
struct Node* ptr = graph->head[i];
while (ptr != NULL)
{
printf("(%d —> %d)\t", i, ptr->dest);
ptr = ptr->next;
}
printf("\n");
}
}
int main(void)
{
struct Edge edges[] =
{
{0, 1}, {1, 2}, {2, 0}, {2, 1}, {3, 2}, {4, 5}, {5, 4}
};
int n = sizeof(edges)/sizeof(edges[0]);
struct Graph *graph = createGraph(edges, n);
printGraph(graph);
return 0;
}