Push every node to the queue which has no incoming edge
for ( int i = 0 ; i < V ; i ++ ) { if ( indeg . get ( i ) == 0 ) { q . add ( i ) ; } } ArrayList < Integer > res = new ArrayList < Integer > ( ) ; while ( q . size ( ) > 0 ) { int u = q . poll ( ) ; res . add ( u ) ;