'How can I access and iterate through an ArrayList of Linked list element?

I am trying to write a code of adjacency list implementation of the graph ADT.

 private ArrayList<LinkedList<Integer>> adjLists ;

but I don't know how to iterate through the vertices of the graph...



Solution 1:[1]

errr... You just go through every elements...

for(int i = 0;i<adjLists.size();i++){
   for(int j = 0;j<adjLists.size();j++){
       int element = adjLists.get(i).get(j);
        //Then do whatever you want
   }
}

Solution 2:[2]

Here's a complete Graph class implemented using ArrayList<LinkedList>

import java.util.*;

public class Graphs {

    private ArrayList<LinkedList<Integer>> list;

    public Graphs(int vertices) {
        list = new ArrayList<>(vertices);
        for (int i = 0; i < vertices; i++) {
            list.add(i, new LinkedList<>());
        }
    }

    public void addEdge(int v1, int v2) {
        list.get(v1).add(v2);
        list.get(v2).add(v1);
    }

    public void print() {
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < list.get(0).size(); j++) {
                System.out.print(list.get(i).get(j) + " -> ");
            }
            System.out.print("null");
            System.out.println("");
        }
    }

    public void bfs(int soucevertex) {
        ArrayList<Boolean> visited = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            visited.add(false);
        }
        Queue<Integer> queue = new LinkedList<>();
        queue.add(soucevertex);
        visited.set(soucevertex, true);
        while (!queue.isEmpty()) {
            for (int i = 0; i < list.get(queue.peek()).size(); i++) {
                if (visited.get(list.get(queue.peek()).get(i)) == false) {
                    visited.set(list.get(queue.peek()).get(i), true);
                    queue.add(list.get(queue.peek()).get(i));
                }
            }
            System.out.print(queue.poll() + " ");
        }
    }

    public void dfs(int sourcevertex) {
        ArrayList<Boolean> visited = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            visited.add(false);
        }
        dfsutil(sourcevertex, visited);
    }

    private void dfsutil(int source, ArrayList<Boolean> visited) {
        visited.set(source, true);
        System.out.print(source + " ");
        for (int i = 0; i < list.get(source).size(); i++) {
            if (visited.get(list.get(source).get(i)) == false) {
                dfsutil(list.get(source).get(i), visited);
            }
        }
    }

}



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lier wu
Solution 2 Nisab Mohd