-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement_Graph_Data_Structure_in_C++_Weighted_Directed_Graph.cpp
More file actions
71 lines (60 loc) · 1.53 KB
/
Copy pathImplement_Graph_Data_Structure_in_C++_Weighted_Directed_Graph.cpp
File metadata and controls
71 lines (60 loc) · 1.53 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
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "iostream"
using namespace std;
struct Edge {
int source,destination,weight;
};
struct Node{
int destination;
int weight;
Node * next;
};
class Graph{
Node * getAdjListNode(int destination,Node * head ,int weight ){
Node * newNode = new Node;
newNode->destination = destination;
newNode->weight = weight;
newNode->next = head;
return newNode;
}
public:
Node ** head;
int N;
Graph(Edge edges[],int noOfEdges,int N){
head = new Node * [N]();
this->N = N;
for (int i = 0; i < N; ++i) head[i] = nullptr;
for (int j = 0; j < noOfEdges; ++j) {
head[edges[j].source] = this->getAdjListNode(edges[j].destination,head[edges[j].source],edges[j].weight);
}
}
~Graph() {
for (int i = 0; i < N; i++)
delete[] head[i];
delete[] head;
}
};
void printGraph(Graph graph){
for (int i = 0; i < graph.N; ++i) {
Node * ptr = graph.head[i];
cout << i <<"--";
while (ptr != nullptr)
{
cout << " -> " << ptr->destination<<" ("<<ptr->weight<<") " << " ";
ptr = ptr->next;
}cout <<"\n";
}
cout << endl;
}
int main()
{
Edge edges[] =
{
{ 0, 1, 6 }, { 1, 2, 7 }, { 2, 0, 5 }, { 2, 1, 4 },
{ 3, 2, 10 }, { 4, 5, 1 }, { 5, 4, 3 }
};
int N = 6;
int n = sizeof(edges)/sizeof(edges[0]);
Graph graph(edges, n, N);
printGraph(graph);
return 0;
}