File tree 1 file changed +17
-1
lines changed
src/main/java/com/packt/datastructuresandalg/lesson6/graph
1 file changed +17
-1
lines changed Original file line number Diff line number Diff line change @@ -7,14 +7,29 @@ public class AdjacencyListGraph {
7
7
8
8
public AdjacencyListGraph (int nodes ) {
9
9
this .adj = new ArrayList [nodes ];
10
+ for (int i = 0 ; i < nodes ; i ++)
11
+ this .adj [i ] = new ArrayList <>();
10
12
}
11
13
12
14
public void addEdge (int u , int v ) {
13
15
adj [u ].add (v );
14
16
}
15
17
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
+
16
31
public static void main (String [] args ) {
17
- AdjacencyListGraph g = new AdjacencyListGraph (5 );
32
+ AdjacencyListGraph g = new AdjacencyListGraph (6 );
18
33
g .addEdge (0 , 1 );
19
34
g .addEdge (0 , 3 );
20
35
g .addEdge (1 , 4 );
@@ -23,5 +38,6 @@ public static void main(String [] args) {
23
38
g .addEdge (3 , 1 );
24
39
g .addEdge (4 , 3 );
25
40
g .addEdge (5 , 5 );
41
+ System .out .println (g );
26
42
}
27
43
}
You can’t perform that action at this time.
0 commit comments