Description

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Ideas

當純的linked list的操作,注意進位時的處理就好。


Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    var head = new(ListNode)
    cur := head
    carry := 0

    for l1 != nil || l2 != nil || carry > 0 {
        if l1 != nil {
            carry += l1.Val
            l1 = l1.Next
        }
        if l2 != nil {
            carry += l2.Val
            l2 = l2.Next
        }
        cur.Next = new(ListNode)
        cur.Next.Val = carry%10
        cur = cur.Next
        carry /= 10
    }
    return head.Next
}