-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphimplementationusingadjlist.cpp
98 lines (84 loc) · 2.1 KB
/
graphimplementationusingadjlist.cpp
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
//Convert given adjacent matrix for graph into adjacent list
#include<iostream>
#include<cstring>
using namespace std;
struct edgeGraph
{
int start_ver, end_ver, weight;
};
struct adjNode
{
int end_ver, weight;
adjNode* next;
};
class diaGraph
{
private:
int V, E;
/*
This function can also be used to create and add Nodes
adjNode* addadjNode(int end_ver, int weight, adjNode* next)
{
adjNode* newNode = new adjNode;
newNode->end_ver = end_ver;
newNode->weight = weight;
newNode->next = next;
return newNode;
}
*/
public:
adjNode** head;
diaGraph(edgeGraph edges[], int V, int E)
{
this->V = V;
this->E = E;
//head is a array which stores first adjacentNode address which then points next remaining till NULL
head = new adjNode*[V];
for(int i=0; i<V; i++)
{
head[i] = nullptr;
}
for(int i=0; i<E; ++i)
{
//head[edges[i].start_ver] = addadjNode(edges[i].end_ver, edges[i].weight, head[edges[i].start_ver]);
adjNode* newNode = new adjNode;
newNode->end_ver = edges[i].end_ver;
newNode->weight = edges[i].weight;
newNode->next = head[edges[i].start_ver];
head[edges[i].start_ver] = newNode;
}
}
~diaGraph()
{
for(int i=0; i<V; i++)
delete[] head[i];
delete[] head;
}
};
void printAdjNodes(adjNode* ptr)
{
while(ptr!=nullptr)
{
cout<<ptr->end_ver<<":"<<ptr->weight<<"->";
ptr = ptr->next;
}
}
int main()
{
//manually giving number of vertices and inserting edges
int V = 5;
edgeGraph edges[] = {
{0,1,3}, {0,4,7}, {1,2,8}, {1,3,5}, {2,3,7}, {3,4,6}, {4,0,4}, {4,1,5}
};
//Calculating number of edges
int E = sizeof(edges)/sizeof(edges[0]);
//constructing a directional graph using edgelist
diaGraph diagraph(edges, V, E);
//printing the diagraph
for(int i=0; i<V; i++)
{
cout<<i<<"->";
printAdjNodes(diagraph.head[i]);
cout<<endl;
}
}