4 Creating Adjacency Lists

An undirected graph G = V , E G=(V,E) is represented by the sets V G V(G) and E G E(G) . If these sets are maintained as simple lists where the buffer v v communicates with the vertex list and e e communicates with the edge list, Algorithm 1 creates an adjacency list A A for G G .

Algorithm 1: Create Adjacency List of Undirected Graph
i = i= first( V V )
while  k e o l k\neq eol
    insert( A , v , h e a d e r A,v,header )
     k = k= next( V , k V,k )
k = k= first( E E )
while  k e o l k\neq eol
    insert( A , e . v , e . w A,e.v,e.w )
    insert( A , e . w , e . v A,e.w,e.v )
     k = k= next( E , k E,k )

The first loop in Algorithm 1 creates a header for each vertex. This operation is not strictly necessary given the current data definition; however, it is often required in practical implementations.

You should observe that the algorithm inserts each edge in E G E(G) into the adjacency list twice: once in the stated direction and once in the reverse direction. If G G is a directed graph, the reverse insertion is inappropriate (i.e. omit the final insert statement in Algorithm 1). It should be apparent that the algorithm has a time complexity of O V + E O\left(|V|+|E|\right) if all operators have time complexity of O 1 O(1) .

It is often beneficial to create an adjacency list based on an alternate labeling of the vertices of G G . This operation requires a mapping μ \mu of the integers from 1 to V |V| onto the set V G V(G) . Algorithm 2 maps V G V(G) to the order in which it is enumerated.

Algorithm 2: Map Vertices To Labeling Order
i = 0 i=0
k = k= first( V V )
while  k e o l k\neq eol
     i = i + 1 i=i+1
    map( μ , v , i \mu,v,i )
     k = k= next( V , k V,k )

Algorithm 3 combines these two procedures. It labels V G V(G) according to its order of enumeration and creates an adjacency list based on this labeling.

Algorithm 3: Create Ordered Adjacency List
i = 0 i=0
k = k= first( V V )
while  k e o l k\neq eol
     i = i + 1 i=i+1
    map( μ , v , i \mu,v,i )
    insert( A , v , h e a d e r A,v,header )
     k = k= next( V , k V,k )
k k  = first( E E )
while  k e o l k\neq eol
     i = i= evaluate( μ , e . v \mu,e.v )
     j = j= evaluate( μ , e . w \mu,e.w )
    insert( A , i , j A,i,j )
    insert( A , j , i A,j,i )
     k = k= next( E , k E,k )

If map and evaluate have constant time complexity, the overall algorithm retains its linear complexity.

Note. In a practical implementation, map will insert the pair d , r (d,r) into a data structure that is optimized for searching and evaluate will look up d d in this data structure. Efficient operations of this sort have a time complexity of O log 2 n O\left(\,\log _{2}n\,\right) . Therefore, adjacency list creation will have complexity O V log 2 V + E log 2 V O\left(\,|V|\log _{2}|V|+|E|\log _{2}|V|\,\right) .