def sum_list2(h1, h2):
    h1, h2 = pad_list(h1, h2)
    node, acc = deep_sum(h1, h2)
    if acc != 0:
        n = Node(acc)
        n.append_node(node)
        node = n
    return node
def deep_sum(h1, h2):
    if h1.next == None and h2.next == None:
        val = (h1.data + h2.data) % 10
        acc = (h1.data + h2.data) / 10
        return Node(val), acc
    else:
        node, acc = deep_sum(h1.next, h2.next)
        val = h1.data + h2.data + acc
        tmp, acc = val % 10, val / 10
        n = Node(tmp)
        n.append_node(node)
        return n, acc
def pad_list(h1, h2):
    c1, c2 = h1, h2
    l1, l2 = 0,0
    while c1 != None:
        l1 += 1
        c1 = c1.next
    while c2 != None:
        l2 += 1
        c2 = c2.next

    if l1 < l2:
        h = Node(0)
        padding = [0 for _ in xrange(l1 - l2 - 1)]
        h.append_array(padding)
        h.append_node(h1)
        return h, h2
    elif l1 > l2:
        h = Node(0)
        padding = [0 for _ in xrange(l2 - l1 - 1)]
        h.append_array(padding)
        h.append_node(h2)
        return h1, h
    else:
        return h1, h2
print "3rd to last of [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]", kth_to_last(head, 3).data == 3
print "0th to last of [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]", kth_to_last(head, 0).data == None

""" Delete middle node
Implement a algorithm to delete a node in the middle (not first nor last) of a single linked list given only access to that node
"""

def delete_middle_node(middle):
    middle.data = middle.next.data
    middle.next = middle.next.next

head = Node(5)
middle = Node(10)
head.append_array([1, 2, 3])
middle.append_array([3, 2, 1])
head.append_node(middle)
delete_middle_node(middle)
print head.to_list() == [5, 1, 2, 3, 3, 2, 1]

""" Partition
Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater or equal to x.
If x is contained within the list, the value of x the value of x only need to be after the element less than x. The partition element x can appear anywhere in the right partition; it does not need to appear between the left and the right partitions.
Example:
[input] [3, 5, 8, 5, 10, 2, 1] partition 5
[output] [3, 1, 2, 10, 5, 5, 8]
"""

""" Sum Lists
You have two numbers represented by a libnked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
Example:
[7, 1, 6] + [5, 9, 2] => [2, 1, 9]