DoubleLinkedList#delete_at

This commit is contained in:
Philippe PITTOLI 2024-05-26 03:19:38 +02:00
parent 89e29324ff
commit 981cdc92b8
2 changed files with 25 additions and 0 deletions

View File

@ -101,4 +101,11 @@ describe "DoubleLinkedList" do
list.pop
list.peek.value.should eq 3
end
it "delete_at" do
list = DoubleLinkedList(Int32).new
list << 1 << 2 << 3 << 4
list.delete_at(2).value.should eq 3
list.to_s.should eq "[ 1, 2, 4 ]"
end
end

View File

@ -88,6 +88,24 @@ class DoubleLinkedList(V)
new_node
end
# Removes an entry at an index.
def delete_at(index : Int32) : Node(V)
if index == 0
shift
elsif index == @size - 1
pop
else
v = self[index]
prev_node = v.previous.not_nil!
next_node = v.next.not_nil!
prev_node.next = next_node
next_node.previous = prev_node
@size -= 1
v
end
end
# Adds a *value* to the linked list at a specified index.
#
# ```