-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement_Graph_Data_Structure_in_C_Directed_Graph.c
More file actions
49 lines (42 loc) · 1.22 KB
/
Copy pathImplement_Graph_Data_Structure_in_C_Directed_Graph.c
File metadata and controls
49 lines (42 loc) · 1.22 KB
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
#include<stdio.h>
#include<stdlib.h>
#define N 6
struct Node{
int destination;
struct Node * next;
};
struct Edge{
int source,destination;
};
struct Graph{
struct Node * head [N];
};
struct Graph * createGraph(struct Edge edges[], int noOfEdges) {
struct Graph * graph = (struct Graph *)malloc(sizeof(struct Graph));
for (int i = 0; i < N; ++i) graph->head[i] = NULL;
for (int j = 0; j < noOfEdges; ++j) {
struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->destination = edges[j].destination;
newNode->next = graph->head[edges[j].source];
graph->head[edges[j].source] = newNode;
}
return graph;
}
void printGraph(struct Graph * graph){
for (int i = 0; i < N; ++i) {
struct Node * temp = graph->head[i];
while(temp){ printf("(%d -> %d)",i,temp->destination);temp = temp->next;}printf("\n");
}
}
int main(void)
{
struct Edge edges[] =
{
{ 0, 1 }, { 1, 2 }, { 2, 0 }, { 2, 1 },
{ 3, 2 }, { 4, 5 }, { 5, 4 }
};
int noOfEdges = sizeof(edges)/sizeof(edges[0]);
struct Graph *graph = createGraph(edges, noOfEdges);
printGraph(graph);
return 0;
}