Created
June 17, 2015 14:29
-
-
Save matugm/f6b56400044ec02deaa1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ListNode | |
attr_accessor :val, :next | |
def initialize(val) | |
@val = val | |
@next = nil | |
end | |
end | |
@carry = false | |
def add_nodes(l1,l2) | |
total = l1.val + l2.val | |
if @carry | |
total += 1 | |
@carry = false | |
end | |
if total > 9 | |
total = total % 10 | |
@carry = true | |
end | |
create_node(total) | |
end | |
def add_two_numbers(l1, l2) | |
@carry = false | |
add_two_numbers_real(l1, l2) | |
end | |
def add_two_numbers_real(l1, l2) | |
return create_node(1) if @carry and !l1 | |
return unless l1 or l2 | |
l2 = create_node(0) unless l2 | |
l1 = create_node(0) unless l1 | |
node = add_nodes(l1, l2) | |
node.next = add_two_numbers_real(l1.next, l2.next) | |
node | |
end | |
module List | |
def create_list(values) | |
recursive_append_multiple(values) | |
# head = create_node(values.shift) | |
# values.each { |n| head = append_node(head, n) } | |
# head | |
end | |
def create_node(value) | |
ListNode.new value | |
end | |
def recursive_append_multiple(values, idx = 0) | |
return if idx >= values.size | |
node = create_node(values[idx]) | |
node.next = recursive_append_multiple(values, idx+1) | |
node | |
end | |
# Loop until node.next = nil | |
def append_node(node, value) | |
node.tap { | |
while node.next | |
node = node.next | |
end | |
node.next = create_node(value) | |
} | |
end | |
end | |
include List | |
list_1 = create_list [3,2,1] | |
list_2 = create_list [3,2,1] | |
one = create_list [1] | |
five = create_list [5] | |
list_3 = create_list [1,8] | |
zero = create_list [0] | |
p add_two_numbers one, five | |
p add_two_numbers five, five | |
p add_two_numbers list_1, list_2 | |
p add_two_numbers list_3, zero | |
p add_two_numbers create_list([9]), create_list([9]) | |
p add_two_numbers create_list([9,9]), create_list([1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment