Java implementation of adjacency list

Jw123 picture Jw123 · Feb 9, 2013 · Viewed 19.4k times · Source

I have a n*m matrix with integer value at each node and its an undirected graph. I want to build an adjacency list for it. How do I do that? Any help is much appreciated.

Answer

Sumeet picture Sumeet · Jan 26, 2015

Here is a simple implementation for creating adjacency list.According to the problem:

There will be n linked lists each of variable size.

First Initialize an ArrayList of linked lists of integers:

ArrayList<LinkedList<Integer>> adj_list = new ArrayList<LinkedList<Integer>>();

Then simply add linked lists by repeating following code:

adj_list.add(new LinkedList<Integer>());

If you are using it to represent graph,then no of linked lists=no of vertices.So you must repeat the above line n(no of vertices) times.

Say now you want to add numbers 3,4,5 to your first linked lists.Do the following:

adj_list.get(0).add(3);
adj_list.get(0).add(4);
adj_list.get(0).add(5);

It simply means there is an edge in your graph from vertex 0 to 3,4,5.