这题最好还是不要全部算出来答案在依次分配位数吧,不然0offer。
注意点:一个节点可以指向多个节点,但是会被依次覆盖,这个以前还真没用过,没想到编译过了
# -*- coding: UTF-8 -*-
# Definition for singly-linked list.
# class ListNode: # 定义链表节点类
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
if l2 is None:
return l1
carry = 0
res= l3 = ListNode(0)
while l1 or l2:
temp = 0
if l1:
temp = l1.val
l1 = l1.next
if l2:
temp += l2.val
l2 = l2.next
res.next = ListNode((temp + carry) % 10)
carry = (temp + carry) //10
res = res.next
if carry:
res.next=ListNode(carry)
return l3.next