解题思路
这道题其实跟字符串相加类似,我们可以用相同的思路来解这道题。
因为它们每位数字都是按照逆序的顺序来存储的,所以在思考两个链表长短问题的时候不用考虑那个数字大那个数字小,两个链表的头节点都是个位数,然后是十位数以此类推。
算法过程
- 创建
cur
,head
变量辅助,其中cur
负责指针操作,head
作为最终结果 - 同时创建变量
carry
,作为加法运算是存储的进位 - 开始遍历连个链表
l1, l2
, 对它们的每一位进行加法运算,将结果取余然后以新节点的方式存入 - 最后再更新
carry
,注意当遍历完两个链表时,如果进位还存在需要再进一位
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head, cur = None, None
carry = 0
while l1 or l2:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
sums = x + y + carry
if head is None: head = cur = ListNode(sums % 10)
else:
cur.next = ListNode(sums % 10)
cur = cur.next
carry = sums // 10
if l1: l1 = l1.next
if l2: l2 = l2.next
if carry > 0:
cur.next = ListNode(carry)
return head