// IncidenceList.java import java.util.LinkedList; class Graph { // a class for storing an edge of the graph private class Edge { public int to; public int cost; public Edge(int to, int cost) { this.to = to; this.cost = cost; } // this is so we can search for edges by destination public boolean equals(Object other) { Edge otherEdge = (Edge) other; return to == otherEdge.to; } } // an array of linked lists, each list holds the edges out of that node private LinkedList[] nodes; // construct an empty graph of a given size public Graph(int size) { // becasue this is a generic array, we need to cast nodes = (LinkedList[]) new LinkedList[size]; for (int i = 0; i < size; i++) { nodes[i] = new LinkedList(); } } // insert an edge public void insert(int from, int to, int cost) { nodes[from].add(new Edge(to, cost)); } // remove an edge public void remove(int from, int to) { nodes[from].remove(new Edge(to, -1)); } // return the cost of an edge or 0 for none public int getCost(int from, int to) { // search the linked list for this edge int index = nodes[from].indexOf(new Edge(to, -1)); // if -1, return 0 // else return the cost of that edge if (index == -1) { return 0; } else { return nodes[from].get(index).cost; } } } public class IncidenceList { public static void main(String args[]) { // create a graph with 6 nodes Graph graph = new Graph(6); // add the edges graph.insert(0, 3, 15); graph.insert(0, 4, 20); graph.insert(1, 5, 25); graph.insert(3, 0, 15); graph.insert(3, 1, 25); graph.insert(4, 2, 30); graph.insert(4, 5, 10); graph.insert(5, 1, 25); } }