leetcode题解2:Add Two Numbers

/ 默认分类 / 没有评论 / 124浏览

题目链接:Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    head := &ListNode{0,nil}
    current := head
    carry := 0
    pre := head
    for l1!= nil || l2 != nil || carry != 0 {
        current.Val = carry
        if l1 != nil {
            current.Val += l1.Val
            l1 = l1.Next
        }
        if l2 != nil {
            current.Val += l2.Val
            l2 = l2.Next
        }
        carry = current.Val/10
        current.Val = current.Val%10
        current.Next = new(ListNode)
        pre = current
        current = current.Next
    }
    if current.Val == 0 {
        pre.Next=nil
    }
    return head
    
}