File tree Expand file tree Collapse file tree 1 file changed +17
-1
lines changed
src/main/java/com/packt/datastructuresandalg/lesson6/graph Expand file tree Collapse file tree 1 file changed +17
-1
lines changed Original file line number Diff line number Diff line change @@ -7,14 +7,29 @@ public class AdjacencyListGraph {
77
88 public AdjacencyListGraph (int nodes ) {
99 this .adj = new ArrayList [nodes ];
10+ for (int i = 0 ; i < nodes ; i ++)
11+ this .adj [i ] = new ArrayList <>();
1012 }
1113
1214 public void addEdge (int u , int v ) {
1315 adj [u ].add (v );
1416 }
1517
18+ @ Override
19+ public String toString () {
20+ String res = "" ;
21+ for (int i = 0 ; i < adj .length ; i ++) {
22+ res += (i + ":" );
23+ for (int j = 0 ; j < adj [i ].size (); j ++)
24+ res += (" " + adj [i ].get (j ));
25+ if (i + 1 < adj .length )
26+ res += "\n " ;
27+ }
28+ return res ;
29+ }
30+
1631 public static void main (String [] args ) {
17- AdjacencyListGraph g = new AdjacencyListGraph (5 );
32+ AdjacencyListGraph g = new AdjacencyListGraph (6 );
1833 g .addEdge (0 , 1 );
1934 g .addEdge (0 , 3 );
2035 g .addEdge (1 , 4 );
@@ -23,5 +38,6 @@ public static void main(String [] args) {
2338 g .addEdge (3 , 1 );
2439 g .addEdge (4 , 3 );
2540 g .addEdge (5 , 5 );
41+ System .out .println (g );
2642 }
2743}
You can’t perform that action at this time.
0 commit comments