题目描述
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
主要思路: 链表的第一个数字是个位数,第二个数字是十位数,以此类推。那么如果两个链表中有一个不为空,遍历两个链表,记录两个链表第一个节点与进位(一个 in 类型变量,为 0 或 1)之和(记为 total),记录完成之后将进位清零。如果 total 不超过十,那么它就是结果链表的个位数;否则,将其减去十,并将进位设置为1,其他位一样。设置结果链表的当前节点值为 total。如果两个链表都遍历完了,仍然有一个进位,那么设置结果链表的最后一个节点为1,最后返回结果链表。
// golang 版本
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
result := &ListNode{}
current := result
v1, v2, carry := 0, 0, 0
for l1 != nil || l2 != nil {
if l1 != nil {
v1 = l1.Val
l1 = l1.Next
}
if l2 != nil {
v2 = l2.Val
l2 = l2.Next
}
total := v1 + v2 + carry
v1, v2, carry = 0, 0, 0
if total >= 10 {
total -= 10
carry = 1
}
current.Val = total
if l1 != nil || l2 != nil || carry == 1 {
current.Next = &ListNode{}
current = current.Next
}
}
if carry == 1 {
current.Val = carry
}
return result
}
# python 版本
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
result = ListNode(0)
current = result
v1 = v2 = carry = 0
while l1 or l2:
if l1 is not None:
v1 = l1.val
l1 = l1.next
if l2 is not None:
v2 = l2.val
l2 = l2.next
total = v1 + v2 + carry
v1 = v2 = carry = 0
if total >= 10:
total -= 10
carry = 1
current.val = total
if l1 or l2 or carry:
current.next = ListNode(0)
current = current.next
if carry == 1:
current.val = carry
return result