I was trying to implement some graph related problem. To represent the graph, I used adjacency list using std::list, something like this,
list<int> *adj;
adj = new list<int>[V];
where V is the total vertices.
then I took all the edges(directed) and store them using the function,
void addEdge(int u, int v) {   //  when u points to v
     adj[u].push_back(v);
}
So the graph looks like this:
Everything works fine, but I want to add a new vertex. I was trying to adjust my adj list, but I can't do that. What I did, I make a copy of it, then delete adj and make a new adj with higher size, and finally copy back all the previous adjacency list into it.
Here is my code:
void addVertex() {
        //  backing up the current adjacency list to adj2
        list<int> *adj2 = new list<int>[V];
        for(int s=0; s<V; s++) {
            for(list<int>::iterator i = adj[s].begin(); i != adj[s].end(); i++) {
                adj2[s].push_back(*i);
            }
        }
        delete[] adj;   //  deleting original adjacency list
        ++V;    //  add one vertex.
        adj = new list<int>[V];     //  allocating new adjacency list
        //  resoting adjacency lists back to adj
        for(int s=0; s<V-1; s++) {
            for(list<int>::iterator i = adj2[s].begin(); i != adj2[s].end(); i++) {
                adj[s].push_back(*i);
            }
        }
    }
It works correctly, but I was just wondering if there is any smart way to do that, because every time I want to add a vertex it needs lots of operations.
I tried a lot of things, but didn't find similar question/answer here.
 
     
    