Skip to content

Commit f2b5aee

Browse files
authored
datatypes: fix insert() and delete() for items in second half of DoubleLinkedList[T]{}, add test (#25647)
1 parent d2587eb commit f2b5aee

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

vlib/datatypes/doubly_linked_list.v

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ pub fn (mut list DoublyLinkedList[T]) insert(idx int, item T) ! {
165165
// when idx > list.len/2. This helper function assumes idx bounds have
166166
// already been checked and idx is not at the edges.
167167
fn (mut list DoublyLinkedList[T]) insert_back(idx int, item T) {
168-
mut node := list.node(idx + 1)
168+
mut node := list.node(idx)
169169
mut prev := node.prev
170170
// prev node
171171
// ------ ------
@@ -226,7 +226,7 @@ fn (list &DoublyLinkedList[T]) node(idx int) &DoublyListNode[T] {
226226
return node
227227
}
228228
mut node := list.tail
229-
for t := list.len - 1; t >= idx; t -= 1 {
229+
for t := list.len - 1; t > idx; t -= 1 {
230230
node = node.prev
231231
}
232232
return node

vlib/datatypes/doubly_linked_list_test.v

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,21 @@ fn test_delete() {
136136
assert list.len() == 0
137137
}
138138

139+
fn test_insert_delete() {
140+
mut list := DoublyLinkedList[int]{}
141+
elem := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
142+
list.push_many(elem, Direction.front)
143+
for i in 0 .. 12 {
144+
list.insert(i, 777)!
145+
assert list.array() != elem
146+
r := list.index(777)!
147+
assert r == i
148+
list.delete(r)
149+
assert list.index(777) or { -7 } == -7
150+
assert list.array() == elem
151+
}
152+
}
153+
139154
fn test_iter() {
140155
mut list := DoublyLinkedList[int]{}
141156
for i := 0; i < 10; i++ {

0 commit comments

Comments
 (0)