2022-03-14 10:36:41 +01:00
|
|
|
# nimdeque
|
|
|
|
|
2022-03-15 12:26:09 +01:00
|
|
|
Various deque implementations in pure nim. A deque (short for "double-ended queue") is a data type
|
|
|
|
that is optimized for access towards its ends. A deque's most interesting feauture is the ~O(1)
|
|
|
|
time that it takes to pop/append at either ends (as opposed to regular lists where appending at the
|
|
|
|
beginning is an O(n) operation).
|
|
|
|
|
|
|
|
|
|
|
|
------------------------
|
|
|
|
## Examples
|
|
|
|
|
|
|
|
### LinkedDeque
|
|
|
|
|
|
|
|
A `LinkedDeque` is a deque based on a doubly linked list
|
|
|
|
|
|
|
|
```nim
|
|
|
|
import nimdeque
|
|
|
|
|
|
|
|
|
|
|
|
queue = newLinkedDeque[int]()
|
|
|
|
|
|
|
|
# Appends at the end
|
|
|
|
queue.add(1)
|
|
|
|
queue.add(2)
|
|
|
|
queue.add(3)
|
|
|
|
|
|
|
|
# Prepends at the beginning
|
|
|
|
queue.addLeft(0)
|
|
|
|
queue.addLeft(-1)
|
|
|
|
queue.addLeft(-2)
|
|
|
|
|
|
|
|
# Pops the first element in O(1) time
|
|
|
|
queue.pop(0)
|
|
|
|
|
|
|
|
# Pops the last element in O(1) time
|
|
|
|
queue.pop(queue.high())
|
|
|
|
|
|
|
|
# Supports iteration
|
|
|
|
for i, e in queue:
|
|
|
|
echo i, " ", e
|
|
|
|
|
|
|
|
# Reversed iteration too!
|
|
|
|
for e in queue.reversed():
|
|
|
|
echo e
|
|
|
|
|
|
|
|
echo queue.len()
|
|
|
|
echo 5 in queue # false
|
|
|
|
echo 0 in queue # true
|
|
|
|
|
|
|
|
# Item accessing works just like regular sequence types in Nim.
|
|
|
|
# Note that the further the item is from either end of the
|
|
|
|
# queue, the higher the time it takes to retrieve it. For
|
|
|
|
# fast random access, seqs should be used instead
|
|
|
|
assert queue[0] == -1
|
|
|
|
assert queue[^1] == queue[queue.high()]
|
|
|
|
|
|
|
|
```
|
2022-03-14 18:29:12 +01:00
|
|
|
|
|
|
|
|
|
|
|
__Note__: This is mostly a toy, there are no performance guarantees nor particular optimizations other than very obvious ones. With
|
|
|
|
that said, the collections _do_ work and are tested somewhat thoroughly (please report any bugs!)
|