/** * Graph represented an an adjacency list. * @author ggtowell * Created: dec 1: 2021 */ import java.util.ArrayList; import java.util.HashMap; public class AdjList { /** * Nodes in the array */ private class Node { // Node content public H payload; // hold the list public ArrayList> edges; public Node(H payl) { this.payload = payl; this.edges = new ArrayList>(); } public void addEdge(Node n, double w) { edges.add(new Edge(n, w)); } public String toString() { StringBuffer sb = new StringBuffer(); for (Edge eg : edges) { sb.append(String.format("[%s->%s:%.3f]", payload, eg.too.payload,eg.weight)); } return sb.toString(); } } //Edges in the graph private class Edge { Node too; double weight; public Edge(Node t2, double w) { this.too = t2; this.weight = w; } } // nodes are stored in a hashmap so they are quickly and easily found private HashMap> nodeHash; public AdjList() { nodeHash = new HashMap>(); } @Override public String toString() { StringBuffer sb = new StringBuffer(); for (Node gn : nodeHash.values()) { sb.append(gn.toString()); } return sb.toString(); } public static void main(String[] args) { AdjList adjl = new AdjList<>(); adjl.addNode("A"); adjl.addNode("B"); adjl.addNode("C"); adjl.addNode("D"); adjl.addEdge("A", "B"); adjl.addEdge("A", "D"); adjl.addEdge("B", "D"); adjl.addEdge("C", "D"); adjl.addEdge("C", "B"); adjl.addEdge("C", "A"); adjl.addEdge("D", "B"); System.out.println(adjl); AdjList adji = new AdjList<>(); adji.addNode(1); adji.addNode(2); adji.addEdge(1, 2); adji.addEdge(1, 1); System.out.println(adji); } /** * Add a node to the Graph * Note that initially the node my be unconnected * @param g == the payload of the node **/ public void addNode(G g) { nodeHash.put(g, new Node(g)); } /** * Add an edge with a weight of 1 * @param fr the payload of the node from * @param t2 the payload of the node too */ public void addEdge(G fr, G t2) { addEdge(fr, t2, 1.0); } /** * Add an edge with a weight * @param fr the payload of the node from * @param t2 the payload of the node too * @param w the weight of the edge */ public void addEdge(G fr, G t2, double w) { Node frn = nodeHash.get(fr); Node t2n = nodeHash.get(t2); if (frn == null || t2n == null) return; frn.addEdge(t2n, w); } }