diff --git a/spec/test-lists.cr b/spec/test-lists.cr index 53e1fc2..5444f35 100644 --- a/spec/test-lists.cr +++ b/spec/test-lists.cr @@ -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 diff --git a/src/list.cr b/src/list.cr index df94a1f..29980ac 100644 --- a/src/list.cr +++ b/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. # # ```