programming-examples/ruby/Data_Structures/linked_list_palindrome.rb

23 lines
458 B
Ruby
Raw Normal View History

2019-11-15 12:59:38 +01:00
def palindrome?(head)
stack = []
slow_runner = fast_runner = head
while !fast_runner.nil? && !fast_runner.next.nil?
stack.push(slow_runner.val)
fast_runner = fast_runner.next.next
slow_runner = slow_runner.next
end
unless fast_runner.nil?
slow_runner = slow_runner.next
end
until slow_runner.nil?
temp = stack.pop
return false unless slow_runner.val == temp
slow_runner = slow_runner.next
end
true
end