2. 两数相加

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    newList := &ListNode{
        Val:  0,
        Next: nil,
    }
    firstNode := newList

    for {
        if l1 == nil {
            break
        }
        if l2 == nil {
            break
        }

        if l1 != nil && l2 != nil {
            nextValue := 0
            currentValue := l1.Val + l2.Val
            if currentValue >= 10 {
                currentValue = currentValue - 10
                nextValue = 1

            }
            newList.Next = &ListNode{
                Val:  currentValue,
                Next: nil,
            }
            l1 = l1.Next
            l2 = l2.Next
            if nextValue != 0 {
                if l1 != nil {
                    l1.Val = l1.Val + nextValue
                } else if l2 != nil {
                    l2.Val = l2.Val + nextValue
                } else {
                    l1 = &ListNode{
                        Val:  nextValue,
                        Next: nil,
                    }
                }
            }
            newList = newList.Next
        }
    }

    for {
        if l1 == nil {
            break
        }
        nextValue := 0
        currentValue := l1.Val
        if currentValue >= 10 {
            currentValue = currentValue - 10
            nextValue = 1

        }
        newList.Next = &ListNode{
            Val:  currentValue,
            Next: nil,
        }
        l1 = l1.Next
        if nextValue != 0 {
            if l1 != nil {
                l1.Val += nextValue
            } else {
                l1 = &ListNode{
                    Val:  nextValue,
                    Next: nil,
                }
            }
        }
        newList = newList.Next

    }

    for {
        if l2 == nil {
            break
        }
        nextValue := 0
        currentValue := l2.Val
        if currentValue >= 10 {
            currentValue = currentValue - 10
            nextValue = 1

        }
        newList.Next = &ListNode{
            Val:  currentValue,
            Next: nil,
        }
        l2 = l2.Next
        if nextValue != 0 {
            if l2 != nil {
                l2.Val += nextValue
            } else {
                l2 = &ListNode{
                    Val:  nextValue,
                    Next: nil,
                }
            }
        }

        newList = newList.Next

    }
    return firstNode.Next
}

你可能感兴趣的:(2. 两数相加)