package main
import . "nc_tools"
/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 
 * @param head1 ListNode类 
 * @param head2 ListNode类 
 * @return ListNode类
*/
func addInList( head1 *ListNode ,  head2 *ListNode ) *ListNode {
    // write code here
    head1 = reserve(head1)
    
    head2 = reserve(head2)
    
    j := 0
    dumny := &ListNode{}
    head := dumny
    for head1 != nil || head2 != nil {
        h := j
        if head1 != nil {
            h += head1.Val
            head1 = head1.Next
        }
        if head2 != nil {
            h += head2.Val
            head2 = head2.Next
        }
        
        j = 0
        if h > 9 {
            h -= 10
            j = 1
        }
        
        head.Next = &ListNode{Val:h}
        head = head.Next
    }
    
    if j > 0 {
        head.Next = &ListNode{Val:j}
    }
    
    return reserve(dumny.Next)
}


func reserve(head *ListNode) *ListNode {
    if head == nil || head.Next == nil {
        return head
    }
    
    last := reserve(head.Next)
    head.Next.Next = head
    head.Next = nil
    return last
}