I have written the code below as a BFS implementation. Could someone please review. In particular, I want to know if there could be a memory leak.
#include <iostream>
#include <list>
class Graph
{
int number_of_vertices;
std::list<int> *adjList;
public:
Graph(int number_of_vertices);
void addEdge(int first_vertex, int second_vertex);
void BFS(int vertex);
};
Graph::Graph(int number_of_vertices)
{
this->number_of_vertices = number_of_vertices;
adjList = new std::list<int>[number_of_vertices]; // Allocates space for list equal to number_of_vertices.
}
void Graph::addEdge(int first_vertex, int second_vertex)
{
adjList[first_vertex].push_back(second_vertex);
}
void Graph::BFS(int vertex)
{
bool *visited = new bool [number_of_vertices];
for (int i = 0; i < number_of_vertices; i++)
{
visited[i] = false;
}
visited[vertex] = true; // Mark the vertex as visited
std::list<int> queue;
queue.push_back(vertex);
while(!queue.empty())
{
vertex = queue.front();
std::cout << vertex << " ";
queue.pop_front();
for(auto it = adjList[vertex].cbegin(); it!= adjList[vertex].cend(); ++it)
{
if(!visited[*it])
{
visited[*it] = true; // Mark the vertex as visited
queue.push_back(*it);
}
}
}
}
// Driver Program
int main()
{
// Create a graph
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
std::cout << "Following is Breadth First Traversal "
<< "(starting from vertex 2) \n";
g.BFS(2);
return 0;
}