DoubleLinkedList#delete_at
parent
89e29324ff
commit
981cdc92b8
|
@ -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
|
||||
|
|
18
src/list.cr
18
src/list.cr
|
@ -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.
|
||||
#
|
||||
# ```
|
||||
|
|
Loading…
Reference in New Issue