Search⌘ K
AI Features

Adjacency List Representation - Implementation

Understand how to implement the adjacency list representation for graphs in C++. Learn to add edges, handle directed and undirected graphs, and print adjacency lists to visualize graph structure.

We'll cover the following...

Implementation

This implementation requires basic knowledge of vectors. Let us jump right into the code.

C++
#include<iostream>
#include<list>
using namespace std;
class Graph
{
int V;
list<int> *l;
public:
Graph(int v)
{
V = v;
l = new list<int>[V]; //Array of Linked Lists
}
void addEdge(int u,int v,bool bidir=true)
{
l[u].push_back(v);
if(bidir)
l[v].push_back(u);
}
void printAdjList()
{
for(int i=0;i<V;i++)
{
cout<<i<<"->";
for(int vertex: l[i])
cout<<vertex<<",";
cout<<endl;
}
}
};
int main(){
// Graph has 5 vertices number from 0 to 4
Graph g(5);
g.addEdge(0,1);
g.addEdge(0,4);
g.addEdge(4,3);
g.addEdge(1,4);
g.addEdge(1,2);
g.addEdge(2,3);
g.addEdge(1,3);
g.printAdjList();
return 0;
}

Explanation:

  • On line 4, we define our class Graph to create a graph structure.
  • On line 6, we define an integer
...