// Stephanie's class notes. // sorely missing comments and docstrings. sorry. // Graph implemented with adjacency set // Note: I have implemented the graph as a digraph. If you want to connection // node A to node B, it puts in an edge from A to B, but not the corresponding // edge from B to A. import java.util.*; public class Graph3 { private HashSet nodes; public static class GraphNode { private HashSet neighbors; String label; public GraphNode() { this.neighbors = new HashSet(); this.label = ""; } public GraphNode(String label) { this.neighbors = new HashSet(); this.label = label; } public void connectTo( GraphNode other ) { this.neighbors.add( other ); } public String toString() { String ret = this.label + ":"; for (GraphNode n: this.neighbors) ret += " " + n.label; return ret; } } // end class GraphNode public Graph3() { nodes = new HashSet(); } public void connect( GraphNode fromNode, GraphNode toNode ) { if (! this.nodes.contains( fromNode )) this.nodes.add( fromNode ); if (! this.nodes.contains( toNode )) this.nodes.add( toNode ); fromNode.connectTo( toNode ); } public void printAll() { for (GraphNode n: nodes) System.out.println( n ); } public static void main( String[] args ) { Graph3 g = new Graph3(); GraphNode n1 = new GraphNode( "n1" ); GraphNode n2 = new GraphNode( "n2" ); GraphNode n3 = new GraphNode( "n3" ); g.connect( n1, n2 ); g.connect( n3, n2 ); g.printAll(); } }