-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph-Adjacency_List_using_Class.cpp
More file actions
61 lines (53 loc) · 1.04 KB
/
Copy pathGraph-Adjacency_List_using_Class.cpp
File metadata and controls
61 lines (53 loc) · 1.04 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
#include <bits/stdc++.h>
using namespace std;
class Graph
{
private:
int V;
//Array of lists
//we don't know the size of array so using pointer to allocate memory dynamically.
list<int> *l;
public:
Graph(int V)
{
this->V = V;
l = new list<int>[V]; //important, dynamically allocating memory
}
void addEdges(int e1, int e2)
{
l[e1].push_back(e2);
l[e2].push_back(e1);
}
void display(int V)
{
cout << "List representation is : " << endl;
for (int i = 0; i < V; i++)
{
cout << i << " --> ";
list<int>::iterator it;
for (it = l[i].begin(); it != l[i].end(); it++)
cout << *it << " ";
cout << endl;
}
}
};
int main()
{
Graph g(4);
g.addEdges(0, 1);
g.addEdges(0, 2);
g.addEdges(1, 2);
g.addEdges(2, 3);
g.display(4);
return 0;
/*
Graph:
1
/ \
/ \
0----2
|
|
3
*/
}