luoheng
10/6/2019 - 7:28 AM

AddTwoNumbers

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    var head *ListNode
    var p *ListNode
    more := 0
    ans := 0
    for l1 != nil && l2 != nil {
        num1, num2 := l1.Val, l2.Val
        sum := num1 + num2 + more
        ans, more = sum % 10, sum / 10
        if head == nil {
            head = &ListNode{Val:ans}
            p = head
        } else {
            p.Next = &ListNode{Val:ans}
            p = p.Next
        }
        l1 = l1.Next
        l2 = l2.Next
    }
    for l1 != nil {
        num := l1.Val
        sum := num + more
        ans, more = sum % 10, sum / 10
        if head == nil {
            head = &ListNode{Val:ans}
            p = head
        } else {
            p.Next = &ListNode{Val:ans}
            p = p.Next
        }
        l1 = l1.Next
    }
    for l2 != nil {
        num := l2.Val
        sum := num + more
        ans, more = sum % 10, sum / 10
        if head == nil {
            head = &ListNode{Val:ans}
            p = head
        } else {
            p.Next = &ListNode{Val:ans}
            p = p.Next
        }
        l2 = l2.Next
    }
    if more != 0 {
        p.Next = &ListNode{Val: more}
    }
    return head
}