master
 1#!/usr/bin/env ruby
 2
 3=begin
 4You are given two linked-lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
 5
 6Example:
 7
 8  Input:  (2 -> 4 -> 3) + (5 -> 6 -> 4)
 9  Output: (7 -> 0 -> 8)
10
11  Explanation: 342 + 465 = 807.
12
13=end
14
15def assert(x)
16  assert_equal(true, x)
17end
18
19def assert_equal(x, y)
20  raise [x, y].inspect unless x == y
21end
22
23class Node
24  attr_accessor :next
25  attr_reader :value
26
27  def initialize(value)
28    @value = value
29  end
30
31  def equal?(other)
32    self == other
33  end
34
35  def eql?(other)
36    self == other
37  end
38
39  def ==(other)
40    self.value == other&.value && self&.next == other&.next
41  end
42
43  def inspect
44    "#{value}->#{self.next.inspect}"
45  end
46end
47
48class Solution
49  def self.add(left, right)
50    return left if right.nil?
51    return right if left.nil?
52
53    total = left.value + right.value
54    result = Node.new(total % 10)
55    if total >= 10
56      total = total / 10
57      result.next = add(add(Node.new(total), left.next), right.next)
58    else
59      result.next = add(left.next, right.next)
60    end
61    result
62  end
63end
64
65assert Node.new(2).eql?(Node.new(2))
66
67left = Node.new(2)
68left.next = Node.new(4)
69left.next.next = Node.new(3)
70
71right = Node.new(5)
72right.next = Node.new(6)
73right.next.next = Node.new(4)
74
75expected = Node.new(7)
76expected.next = Node.new(0)
77expected.next.next = Node.new(8)
78
79assert_equal(expected, Solution.add(left, right))
80puts "yay!"