Adjacency list representation of graph (nodes with numeric names)
#include<bits/stdc++.h>
using namespace std;
class graph{
private:
int vertices;
list<int> *l;
public:
graph(int v)
{
this->vertices=v;
l=new list<int>[v];
}
void addEdge(int x,int y)
{
l[x].push_back(y);
l[y].push_back(x);
}
void print()
{
for(int i=0;i<vertices;i++)
{
cout<<"Vertex "<<i<<"-> ";
for(auto it=l[i].begin();it!=l[i].end();it++)
cout<<*it<<" ";
cout<<endl;
}
}
};
int main()
{
//g is the object of class graph;
graph g(4);
g.addEdge(2,3);
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(1,2);
g.print();
}
Comments
Post a Comment