I have to reverse a given directed graph, so that the vertices remain the same, but edges are in opposite direction. My graph is represented with a Graph class, which contains an ArrayList of vertices, and each Vertex object has it's number and ArrayList of it's adjacent vertices. My code gives wrong answer, because in each iteration of loop, vertex's adjacent list's size changes. How can I fix my code?
public void reverse() {
ArrayList < Vertex > adjacentOfi = new ArrayList < Vertex > ();
int k;
for (int i = 1; i < verticesSize; i++) {
adjacentOfi = vertices.get(i).getAdjacent();
for (int j = 0; j < adjacentOfi.size(); j++) {
k = adjacentOfi.get(j).getNumber();
adjacentOfi.remove(j);
vertices.get(k).getAdjacent().add(vertices.get(i));
}
}
}
Here is Vertex class
public class Vertex {
private int number;
private boolean marked;
private int finishingTime;
private ArrayList<Vertex> adjacent;
public Vertex(int num) {
this.number = num;
this.marked = false;
this.finishingTime = 0;
this.adjacent = new ArrayList<Vertex>();
}
}
plus of course it's getters and setters. Problem is that when the loops starts from Vertex number 1, and it's adjacency list contains Vertex 5, it adds 1 to 5's adjacency list and deletes 5 from 1's adjacency list. Next time, when loop reaches 5, it adds 5 to 1'a adjacency list and deletes 1 from 5's adjacency list. I need to maintain the initial size of each list, before the loop modifies it.