Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I implement a data structure that preserves order and has fast insertion/removal?
    primarykey
    data
    text
    <p>I'm looking for a data structure that preserves the order of its elements (which may change over the life of the data structure, as the client may move elements around).</p> <p>It should allow fast search, insertion before/after a given element, removal of a given element, lookup of the first and last elements, and bidirectional iteration starting at a given element.</p> <p>What would be a good implementation? </p> <p>Here's my first attempt:</p> <p>A class deriving from both <code>collections.abc.Iterable</code> and <code>collections.abc.MutableSet</code> that contains a linked list and a dictionary. The dictionary's keys are elements, values are nodes in the linked list. The dictionary would handle search for a node given an element. Once an element is found, the linked list would handle insertion before/after, deletion, and iteration. The dictionary would be updated by adding or deleting the relevant key/value pair. Clearly, with this approach the elements must be hashable and unique (or else, we'll need another layer of indirection where each element is represented by an auto-assigned numeric identifier, and only those identifiers are stored as keys).</p> <p>It <em>seems to me</em> that this would be strictly better in asymptotic complexity than either <code>list</code> or <code>collections.deque</code>, but I may be wrong. [EDIT: Wrong, as pointed out by @roliu. Unlike <code>list</code> or <code>deque</code>, I would not be able to find an element by its numeric index in <code>O(1)</code>. As of now, it is <code>O(N)</code> but I am sure there's some way to make it <code>O(log N)</code> if necessary.]</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload