import java.util.LinkedlIst;
class Graph
{
int v;
LinkedList<Integer> a[];
Graph(int v)
{
this.v=v;
a=new LinkedList[5];
for(int i=0;i<v;i++)
{
a[i]=new LinkedList<>();
}
}
void addEdge(int source,int destination)
{
a[source].add(destination);
a[destination].add(source);
}
void printGraph(Graph graph)
{
for(int i = 0; i < v; i++)
{
System.out.println("Adjacency list of vertex "+ i);
System.out.print("head");
for(Integer j: graph.a[i]){
System.out.print(" -> "+j);
}
System.out.println("\n");
}
}
}
class demo{
public static void main(String args[])
{
// create the graph given in above figure
int V = 5;
Graph graph = new Graph(V);
graph.addEdge(0,1);
graph.addEdge(0,4);
graph.addEdge(1,2);
graph.addEdge(1,3);
graph.addEdge(1,4);
graph.addEdge(2,3);
graph.addEdge(3,4);
// print the adjacency list representation of
// the above graph
graph.printGraph(graph);
}
}
class Graph
{
int v;
LinkedList<Integer> a[];
Graph(int v)
{
this.v=v;
a=new LinkedList[5];
for(int i=0;i<v;i++)
{
a[i]=new LinkedList<>();
}
}
void addEdge(int source,int destination)
{
a[source].add(destination);
a[destination].add(source);
}
void printGraph(Graph graph)
{
for(int i = 0; i < v; i++)
{
System.out.println("Adjacency list of vertex "+ i);
System.out.print("head");
for(Integer j: graph.a[i]){
System.out.print(" -> "+j);
}
System.out.println("\n");
}
}
}
class demo{
public static void main(String args[])
{
// create the graph given in above figure
int V = 5;
Graph graph = new Graph(V);
graph.addEdge(0,1);
graph.addEdge(0,4);
graph.addEdge(1,2);
graph.addEdge(1,3);
graph.addEdge(1,4);
graph.addEdge(2,3);
graph.addEdge(3,4);
// print the adjacency list representation of
// the above graph
graph.printGraph(graph);
}
}
No comments:
Post a Comment