输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
1 单个while { 加和 记录carry进位 造链表 } ———— 好
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def addTwoNumbers(l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
p = l1
q = l2
head = ListNode(-1) # 最后再去掉第一个记录节点
cur = head # 分2布 ,保持head不被改
carry = 0
while p or q: # 假 or 假 = 假!
'''(1) if 处理[1,8] [0] 长度不一致时的val值选定'''
num1 = p.val if p else 0
num2 = q.val if q else 0
sum = num1 + num2 + carry
carry = sum // 10 # 个位//10 恰好为0 ,所以不用if sum><0
cur.next = ListNode(sum % 10)
cur = cur.next
'''(2) if 处理[1,8] [0] 超出长度后的循环内None.next'''
p = p.next if p else None
q = q.next if q else None
'''(3) while结束后 处理[5][5] 多一位进位'''
if carry == 1: # carry只有0、1两种!
cur.next = ListNode(1)
return head.next
2 [自己a] 取出数,再加和,再造链表 —— 并列for太多 慢
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
cur = l1
sum1 = 0
i = 0
while cur:
local = cur.val
sum1 += local*(10**i)
i += 1
cur = cur.next
cur = l2
sum2 = 0
i = 0
while cur:
local = cur.val
sum2 += local * (10 ** i)
i += 1
cur = cur.next
needSum = sum1 + sum2
"""个位开始,头插"""
pre = None
count = 0
head = None
while needSum // 10 > 0:
local = needSum % 10
cur = ListNode(local)
count += 1
if count == 1:
head = cur # 存下首指针
if pre: # 避开第一次None.next
pre.next = cur
pre = cur # 放if里面就死循环了 pre出不来
needSum //= 10
"""还差一个百位 【可能01 00 这种和为1位数的也会漏下来 共用的】"""
localNum = needSum % 10
last = ListNode(localNum)
if count == 0: # 先加和这种,不用管5+5=10 这个1不用处理
"""没进入while 要自己创建head ,因为head在while里面创建 导致错误"""
head = last
elif count > 0:
cur.next = last
return head