R3-链表-链表高精度加法
目录
递归法
迭代
递归法
l1.val+l2.val+carry,得到的和,%10为当前位存储的值,除以10为当前的进位值
# 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: Optional[ListNode], l2: Optional[ListNode],carry=0) -> Optional[ListNode]:
#递归边界,如果l1,l2都是空结点
if l1 is None and l2 is None:
if carry:
return ListNode(carry)
return None
if l1 is None:
l1,l2=l2,l1
s=carry+l1.val+(l2.val if l2 else 0)
l1.val=s%10
l1.next=self.addTwoNumbers(l1.next,l2.next if l2 else None,s//10)
return l1
迭代
# 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: Optional[ListNode], l2: Optional[ListNode],carry=0) -> Optional[ListNode]:
#迭代法,感觉有点像模拟这个过程,创建链表,每次保存carry值
#dummy是哨兵结点
cur=dummy=ListNode()
carry=0
while l1 or l2 or carry:
s=carry+(l1.val if l1 else 0)+(l2.val if l2 else 0)
cur.next=ListNode(s%10)
carry=s//10
cur=cur.next
if l1:
l1=l1.next
if l2:
l2=l2.next
return dummy.next