Creating an Adjacency List of a graph
Here is the code:-
#include<bits/stdc++.h>
using namespace std;
class Graph{
int v;
list<int> *l;
public:
Graph(int V){
v=V;
l= new list<int>[v];
}
void addEdge(int i,int j,bool undir=true){
l[i].push_back(j);
if(undir)
l[j].push_back(i);
}
void print(){
for (int i = 0; i < v; i++)
{
cout<<i<<"--> ";
for(auto num:l[i]){
cout<<num<<" ";
}
cout<<endl;
}
}
};
int main(){
Graph g(6);
g.addEdge(0,1);
g.addEdge(3,5);
g.addEdge(4,5);
g.addEdge(1,3);
g.addEdge(1,2);
g.addEdge(2,4);
g.addEdge(2,3);
g.addEdge(3,4);
g.print();
return 0;
}
OutPut-
0--> 1
1--> 0 3 2
2--> 1 4 3
3--> 5 1 2 4
4--> 5 2 3
5--> 3 4
0 Comments
If you have any doubts/suggestion/any query or want to improve this article, you can comment down below and let me know. Will reply to you soon.