Java program to implement the graph data structure
The graph is a data structure that consists of a set of vertices and a set of edges that connect those vertices. In this program, we will implement the graph data structure in Java.
To represent the graph, we will create a class named Graph
. The Graph
class will have two instance variables, vertices
and edges
. The vertices
variable will store the list of vertices in the graph, while the edges
variable will store the list of edges in the graph.
Each vertex in the graph will be represented by a class named Vertex
. The Vertex
class will have an instance variable label
, which will store the label of the vertex.
Each edge in the graph will be represented by a class named Edge
. The Edge
class will have two instance variables, source
and destination
, which will represent the vertices that the edge connects.
Here is the complete program:
refgi:ot reiftidea.comimport java.util.ArrayList; import java.util.List; public class Graph { private List<Vertex> vertices; private List<Edge> edges; public Graph() { vertices = new ArrayList<>(); edges = new ArrayList<>(); } public void addVertex(Vertex v) { vertices.add(v); } public void addEdge(Vertex source, Vertex destination) { edges.add(new Edge(source, destination)); } public List<Vertex> getVertices() { return vertices; } public List<Edge> getEdges() { return edges; } } class Vertex { private String label; public Vertex(String label) { this.label = label; } public String getLabel() { return label; } } class Edge { private Vertex source; private Vertex destination; public Edge(Vertex source, Vertex destination) { this.source = source; this.destination = destination; } public Vertex getSource() { return source; } public Vertex getDestination() { return destination; } }
In this program, we have defined the Graph
, Vertex
, and Edge
classes. The Graph
class has methods to add vertices and edges to the graph, as well as to get the list of vertices and edges in the graph. The Vertex
class has a constructor that takes the label of the vertex, as well as a method to get the label. The Edge
class has a constructor that takes the source and destination vertices of the edge, as well as methods to get the source and destination vertices.
You can use this program to create and manipulate graphs in your Java program.