exist
値がリンクリストのノードとして存在する場合は true を返し、それ以外の場合は false を返す関数を書きたいと思います。これまでのところ、常に true を返す次のコードがあります。どんな助けでも大歓迎です:
class SinglyLinkedList
attr_accessor :head, :tail, :count
def initialize
@head = nil
@tail = nil
@count = 0
end
def insert_front(value)
node = Node.new(value)
if @head.nil?
@head = node
@tail = node
else
node.next = @head
@head = node
end
@count +=1
end
def print_first()
puts head.data
end
def print_last()
puts tail.data
end
def exist(value)
walker = @head
until walker.nil?
if walker.data == value
return true
end
walker = walker.next
end
false
end
def size()
count
end
end
class Node
attr_accessor :data, :next
def initialize(data)
@next = nil
@data = data
end
end
これは私のテストコードです:
list = SinglyLinkedList.new
list.insert_front(1)
list.exist(2)
true を返します。