给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
设置两个临时指针 i、j,初始时分别指向 l1、l2 的第一个节点,i 和 j 每次前进一步,直到 i 为 NULL 或 j 为 NULL,每步都需要设置 i.val:
循环结束后,要么 i 为 NULL,要么 j 为 NULL,要么两者都为 NULL。如果 j 不为 NULL,则将 j 接到 l1 的尾部。之后逐个节点判断是否需要进位。最终 l1 就是要求的结果。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 is None:
return l2
if l2 is None:
return l1
i = l1
j = l2
carry = 0
prev_i = None
while i is not None and j is not None:
i.val = i.val + j.val + carry
if i.val >= 10:
i.val = i.val - 10
carry = 1
else:
carry = 0
prev_i = i
i = i.next
j = j.next
if j is not None:
prev_i.next = j
i = j
while i is not None and carry > 0:
i.val = i.val + carry
if i.val >= 10:
i.val = i.val - 10
carry = 1
else:
carry = 0
prev_i = i
i = i.next
if carry:
prev_i.next = ListNode(1)
return l1