Compare commits

...

2 Commits

Author SHA1 Message Date
89e29324ff DoubleLinkedList: more tests. 2024-05-26 03:07:19 +02:00
ea6017a1c9 Test reverse. 2024-05-26 01:41:49 +02:00
2 changed files with 60 additions and 10 deletions

View File

@ -48,4 +48,57 @@ describe "DoubleLinkedList" do
list.size.should eq 0
end
it "insert_at" do
list = DoubleLinkedList(Int32).new
list.insert_at 2, 0
list.insert_at 1, 0
list.insert_at 3, 2
list.insert_at 0, 0
list.to_s.should eq "[ 0, 1, 2, 3 ]"
end
it "reverse" do
list = DoubleLinkedList(Int32).new
list.reverse.to_s.should eq "[ ]"
list << 1 << 2 << 3 << 4
list.reverse.to_s.should eq "[ 4, 3, 2, 1 ]"
end
it "concat" do
list1 = DoubleLinkedList(Int32).new
list2 = DoubleLinkedList(Int32).new
list1 << 1 << 2
list2 << 3 << 4
list1.concat list2
list1.to_s.should eq "[ 1, 2, 3, 4 ]"
end
it "+" do
list1 = DoubleLinkedList(Int32).new
list2 = DoubleLinkedList(Int32).new
list1 << 1 << 2
list2 << 3 << 4
list3 = list1 + list2
list1.to_s.should eq "[ 1, 2 ]"
list2.to_s.should eq "[ 3, 4 ]"
list3.to_s.should eq "[ 1, 2, 3, 4 ]"
end
it "shift" do
list = DoubleLinkedList(Int32).new
list << 1 << 2 << 3 << 4
list.shift.value.should eq 1
list.shift.value.should eq 2
list.shift.value.should eq 3
list.shift.value.should eq 4
end
it "peek" do
list = DoubleLinkedList(Int32).new
list << 1 << 2 << 3 << 4
list.peek.value.should eq 4
list.pop
list.peek.value.should eq 3
end
end

View File

@ -42,9 +42,9 @@ class DoubleLinkedList(V)
class BrokenList < ::Exception
end
@first : Node(V) | Nil
@last : Node(V) | Nil
@size : UInt32 = 0
property first : Node(V) | Nil
property last : Node(V) | Nil
property size : UInt32 = 0
include Enumerable(V | Nil)
@ -94,7 +94,7 @@ class DoubleLinkedList(V)
# list = DoubleLinkedList(Int32).new
# list << 1 # -> [1]
# list << 2 # -> [1] [2]
# list.insert_at(3, 1) # [1] [3] [2]
# list.insert_at(3, 1) # -> [1] [3] [2]
# ```
# WARNING: this operation is slow, at worst O(n).
def insert_at(value : V, index : Int32) : Node(V)
@ -196,7 +196,7 @@ class DoubleLinkedList(V)
# list = DoubleLinkedList(Int32).new
# list << 1
# list << 2
# list.shift() # -> 1
# list.shift # -> 1
# ```
def shift : Node(V)
if first = @first
@ -213,7 +213,7 @@ class DoubleLinkedList(V)
# ```
# list = DoubleLinkedList(Int32).new(1)
# list << 2
# list.peek() # => 2
# list.peek # => 2
# ```
def peek : Node(V)
if last = @last
@ -264,7 +264,7 @@ class DoubleLinkedList(V)
# values = [1, 2, 3]
# list = DoubleLinkedList(Int32).new(values)
# list.each do |elem|
# puts elem
# puts elem
# end
def each
each_node do |node|
@ -388,15 +388,12 @@ class DoubleLinkedList(V)
# Fancy print of the list's content.
def to_s(io)
io << "[ "
remaining_values = @size
each do |value|
io << value
remaining_values -= 1
io << ", " unless remaining_values == 0
end
io << " ]"
end
end