Merge pull request #9805 from pacien/181126-list-append
add SinglyLinkedList.append procs
This commit is contained in:
commit
239846a528
2 changed files with 17 additions and 1 deletions
|
|
@ -140,11 +140,26 @@ proc contains*[T](L: SomeLinkedCollection[T], value: T): bool {.inline.} =
|
||||||
## exist, true otherwise.
|
## exist, true otherwise.
|
||||||
result = find(L, value) != nil
|
result = find(L, value) != nil
|
||||||
|
|
||||||
|
proc append*[T](L: var SinglyLinkedList[T],
|
||||||
|
n: SinglyLinkedNode[T]) {.inline.} =
|
||||||
|
## appends a node `n` to `L`. Efficiency: O(1).
|
||||||
|
n.next = nil
|
||||||
|
if L.tail != nil:
|
||||||
|
assert(L.tail.next == nil)
|
||||||
|
L.tail.next = n
|
||||||
|
L.tail = n
|
||||||
|
if L.head == nil: L.head = n
|
||||||
|
|
||||||
|
proc append*[T](L: var SinglyLinkedList[T], value: T) {.inline.} =
|
||||||
|
## appends a value to `L`. Efficiency: O(1).
|
||||||
|
append(L, newSinglyLinkedNode(value))
|
||||||
|
|
||||||
proc prepend*[T](L: var SinglyLinkedList[T],
|
proc prepend*[T](L: var SinglyLinkedList[T],
|
||||||
n: SinglyLinkedNode[T]) {.inline.} =
|
n: SinglyLinkedNode[T]) {.inline.} =
|
||||||
## prepends a node to `L`. Efficiency: O(1).
|
## prepends a node to `L`. Efficiency: O(1).
|
||||||
n.next = L.head
|
n.next = L.head
|
||||||
L.head = n
|
L.head = n
|
||||||
|
if L.tail == nil: L.tail = n
|
||||||
|
|
||||||
proc prepend*[T](L: var SinglyLinkedList[T], value: T) {.inline.} =
|
proc prepend*[T](L: var SinglyLinkedList[T], value: T) {.inline.} =
|
||||||
## prepends a node to `L`. Efficiency: O(1).
|
## prepends a node to `L`. Efficiency: O(1).
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,8 @@ const
|
||||||
block SinglyLinkedListTest1:
|
block SinglyLinkedListTest1:
|
||||||
var L: SinglyLinkedList[int]
|
var L: SinglyLinkedList[int]
|
||||||
for d in items(data): L.prepend(d)
|
for d in items(data): L.prepend(d)
|
||||||
assert($L == "[6, 5, 4, 3, 2, 1]")
|
for d in items(data): L.append(d)
|
||||||
|
assert($L == "[6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6]")
|
||||||
|
|
||||||
assert(4 in L)
|
assert(4 in L)
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue