Home > Programming > Adjacency list represention of graph in Java

## Adjacency list represention of graph in Java

Here is the program for adjacency list representation of graphs using java. If you are new to Graphs please read about graphs here before reading the rest of this post.

I used a List data structure inside the graph. I think much explanation is not required because it is very simple.

```import java.io.BufferedReader;
import java.io.IOException;

/**
*
* @author Vasanth Raja Chittampally
*/
class List{
int node;
List next;
}

class Node {
int node;
}

public class Graphs {
void insertVertices() throws IOException
{
System.out.println("Enter number of nodes in a graph: ");
Node g[]=new Node[n];
for (int i = 0; i < n; i++) {
g[i]=new Node();
g[i].node=i+1;
g[i].visit=false;
while(true)
{
System.out.println("Enter zero to stop");
System.out.println("Enter adjacent nodes to node "+(i+1)+" :");
break;
else
{
List l=new List();
l.next=null;
{
}
else
{
while(p.next!=null){
p=p.next;
}
p.next=l;
}
}
}
}
for (int i = 0; i < n; i++) {
System.out.print(g[i].node+" --> ");
while(l!=null)
{
System.out.print(l.node+" --> ");
l=l.next;
}
System.out.println("");
}
}

public static void main(String[] args) throws IOException {
new Graphs().insertVertices();
}

}
```
1. January 25, 2012 at 8:31 pm

The line
g[i].visit=false;
should be left out
eddie

2. March 8, 2012 at 12:28 pm