-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement_Graph_Data_Structure_in_C_Weighted_UnDirected_Graph.cpp
More file actions
58 lines (50 loc) · 1.65 KB
/
Copy pathImplement_Graph_Data_Structure_in_C_Weighted_UnDirected_Graph.cpp
File metadata and controls
58 lines (50 loc) · 1.65 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
50
51
52
53
54
55
56
57
58
#include<stdio.h>
#include<stdlib.h>
#define N 6
struct Node{
int destination,weight;
struct Node * next;
};
struct Edge{
int source,destination,weight;
};
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) {
//for src to dest
struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->destination = edges[j].destination;
newNode->weight = edges[j].weight;
newNode->next = graph->head[edges[j].source];
graph->head[edges[j].source] = newNode;
//for dest to src
struct Node * newNode2 = (struct Node *) malloc(sizeof(struct Node));
newNode2->destination = edges[j].source;
newNode2->weight = edges[j].weight;
newNode2->next = graph->head[edges[j].destination];
graph->head[edges[j].destination] = newNode2;
}
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) (%d) ",i,temp->destination,temp->weight);temp = temp->next;}printf("\n");
}
}
int main(void)
{
struct Edge edges[] =
{
{ 0, 1, 6 }, { 1, 2, 7 }, { 2, 0, 5 }, { 2, 1, 4 },
{ 3, 2, 10 }, { 4, 5, 1 }, { 5, 4, 3 }
};
int noOfEdges = sizeof(edges)/sizeof(edges[0]);
struct Graph *graph = createGraph(edges, noOfEdges);
printGraph(graph);
return 0;
}