/Graph Using Adjacency List

Graph Using Adjacency List

Vertext Class

public class Vertex {
    private Integer data;
    private LinkedList<Integer> edgeslist;
    
    public Vertex(Integer data)
    {
        this.data=data;
        this.edgeslist=new LinkedList();
    }

    public Integer getData() {
        return data;
    }

    public void setData(Integer data) {
        this.data = data;
    }

    public LinkedList<Integer> getEdgeslist() {
        return edgeslist;
    }

    public void setEdgeslist(LinkedList<Integer> edgeslist) {
        this.edgeslist = edgeslist;
    }

    @Override
    public String toString() {
        return "Vertex{" + "data=" + data + ", edgeslist=" + edgeslist + '}';
    }
}

Graph Class

public class Graph {
    
    private Vertex[] vertex;
    private int size;
    private int pos = -1;
    
    public Graph(int size) {
        this.size = size;
        vertex = new Vertex[size];
    }
    
    public void insertVertex(Integer data) {
        this.vertex[++pos] = new Vertex(data);
    }
    
    public LinkedList<Integer> getEdgesofVertex(int pos) {
        return vertex[pos].getEdgeslist();
    }
    
    public void setEdgesofVertex(int pos, LinkedList<Integer> edges) {
        vertex[pos].setEdgeslist(edges);
    }
    
    public void printGraph() {
        for (int i = 0; i < vertex.length; i++) {
            System.out.println(vertex[i].toString());
        }
    }

    public Vertex[] getVertex() {
        return vertex;
    }

    public void setVertex(Vertex[] vertex) {
        this.vertex = vertex;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }
    
    
}

Graph Example Class

import java.util.LinkedList;
import java.util.Scanner;

public class GraphExample {

    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the no of Vertex?");
        int n = scanner.nextInt();
        Graph graph = new Graph(n);
        for (int i = 0; i < n; i++) {
            System.out.println("Enter the vertex at pos " + (i + 1));
            graph.insertVertex(scanner.nextInt());
            System.out.println("Enter the no of Edges at pos " + (i + 1));
            int edgeslength = scanner.nextInt();
            LinkedList<Integer> edges = graph.getVertex()[i].getEdgeslist();
            for (int j = 0; j < edgeslength; j++) {
                System.out.println("Enter Edge?");
                edges.push(scanner.nextInt());
            }
        }

        graph.printGraph();

    }
}