TopVariants of linked listsComparing the complexity of operations

Comparing the complexity of operations

We use big "O" notation to indicate complexity. Let n be the length of a list. We write:

Compare time complexities of operations in implementations using arrays, recursive lists, and singly-linked list:

    clear(), size(),                  // O(1) in array, linked, O(n)
    isEmpty(), getFirst()             // in recursive (but could be fixed)
                                       
    getLast(),                        // O(1) in array, O(n) in
    removeLast()                      // linked, recursive
                                      
    addFirst(Object value);           // O(n) in array, 
    removeFirst();                    // O(1) in linked, recursive

    contains(Object value);           // O(n) in all
    remove(Object value);  

    addLast(Object value);            // O(n) in linked, recursive 
    removeLast(Object value);         // O(1) in array if room

The implementation of lists using linked lists with nodes has the advantage over recursive lists that the list can generally be updated in place, rather than making a new copy. For example, notice that the complexity of adding a new element at the end of a list is very high, as the entire list must be rebuilt from the beginning when adding the element. That is, while the recursive and linked implementations each take time O(n), the constant multiple is higher for the recursive implementation. See the sample code in Linked Lists.


TopVariants of linked listsComparing the complexity of operations