adjacency list building algorithm