Implement a Graph by Linked List


1.Graph.java
import java.util.LinkedList;

public class Graph {

	LinkedList vertex;//LL to store the vertex 
	LinkedList edge;//LL to store the edge of the vertex  

	public Graph () { 
		vertex = new LinkedList();
		edge = new LinkedList();
	} 

	public void addVertex (String name)	{
		vertex.add(name);
	}

	public void addEdge (String snode, String enode) {
		edge.add(new Edge (snode, enode));
	}
	
	public void printVertex(){
		for (String name : vertex){
			System.out.println("The vertex name is: " + name);
		}

	}
	
	public void printEdge(){
		for (Edge e : edge){
			System.out.println(e.toString());			
		}
	}
	
	public static void main(String[] args){
		Graph g = new Graph();
		g.addVertex("A");
		g.addVertex("B");
		g.addVertex("C");
		g.addVertex("D");
		g.addVertex("E");
		g.addVertex("F");
		
		g.addEdge("A", "B");
		g.addEdge("A", "C");
		g.addEdge("B", "D");
		g.addEdge("B", "E");
		g.addEdge("D", "F");
		
		System.out.println("Print all the Vertex");
		g.printVertex();
		
		System.out.println("\nPrint all the Edge");
		g.printEdge();
	}

}

Add Comment