func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    var list *ListNode
    var head *ListNode
    top := 0
    for l1 != nil || l2 != nil {

        n1, n2 := 0, 0
        if l1 != nil {
            n1 = l1.Val
            l1 = l1.Next
        }

        if l2 != nil {
            n2 = l2.Val
            l2 = l2.Next
        }

        sum := n1 + n2 + top
        sum, top = sum%10, sum/10
        if head == nil {
            head = &ListNode{Val: sum}
            list = head
        } else {
            list.Next = &ListNode{Val: sum}
            list = list.Next
        }
    }

    if top > 0 {
        list.Next = &ListNode{Val: top}
    }
    return head
}
Last modification:November 24, 2023
如果觉得我的文章对你有用,请收藏本站