Efficient implementation of immutable (double) LinkedList

前端 未结 3 1311
难免孤独
难免孤独 2020-11-30 05:12

Having read this question Immutable or not immutable? and reading answers to my previous questions on immutability, I am still a bit puzzled about efficient implementation o

3条回答
  •  伪装坚强ぢ
    2020-11-30 05:39

    Should we recursively copy all the references to the list when we insert an element?

    You should recursively copy the prefix of the list up until the insertion point, yes.

    That means that insertion into an immutable linked list is O(n). (As is inserting (not overwriting) an element in array).

    For this reason insertion is usually frowned upon (along with appending and concatenation).

    The usual operation on immutable linked lists is "cons", i.e. appending an element at the start, which is O(1).

    You can see clearly the complexity in e.g. a Haskell implementation. Given a linked list defined as a recursive type:

    data List a = Empty | Node a (List a)
    

    we can define "cons" (inserting an element at the front) directly as:

    cons a xs = Node a xs
    

    Clearly an O(1) operation. While insertion must be defined recursively -- by finding the insertion point. Breaking the list into a prefix (copied), and sharing that with the new node and a reference to the (immutable) tail.

    The important thing to remember about linked lists is :

    • linear access

    For immutable lists this means:

    • copying the prefix of a list
    • sharing the tail.

    If you are frequently inserting new elements, a log-based structure , such as a tree, is preferred.

提交回复
热议问题