#!/usr/bin/python# -*- coding: utf-8 -*-'''
英文:You are given two linked lists representing two non-negative numbers.
The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
中文:两个链表代表两个非负数,每一位倒叙的存储在单个节点上,将两个数相加的结果以链表形式返还
举例:
如342 + 465 = 807,
Input:(2 -> 4 -> 3) + (5 -> 6 -> 4)
Output:7 -> 0 -> 8
'''# Definition for singly-linked list.classListNode(object):def__init__(self, x):
self.val = x
self.next = NoneclassSolution(object):defaddTwoNumbers(self, l1, l2):"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l = ListNode(0)
start = l
last = l
add = 0while l1 and l2:
val = l1.val + l2.val + add
if val > 9:
add,val = divmod(val,10)
else:
add = 0
l.val,l.next = val,ListNode(0)
last = l
l,l1,l2 = l.next,l1.next,l2.next
while l1:
val = l1.val + add
if val > 9:
add,val = divmod(val,10)
else:
add = 0
l.val = val
last = l
l.next = ListNode(0)
l = l.next
l1 = l1.next
while l2:
val = l2.val + add
if val > 9:
add,val = divmod(val,10)
else:
add = 0
l.val = val
last = l
l.next = ListNode(0)
l = l.next
l2 = l2.next
if add: #可能有进位
l.val = add
if l.val == 0: #最后一个节点可能为0节点
last.next = Nonereturn start
优化版
classListNode(object):def__init__(self, x):
self.val = x
self.next = NoneclassSolution(object):defaddTwoNumbers(self, l1, l2):#有缺陷,最后节点有时候不是"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
cur = ListNode(0)
start = cur
carry = 0while l1 or l2:
val1 = l1.val if l1 else0
val2 = l2.val if l2 else0
val = val1 + val2 + carry
carry,val = (0,val) if val < 10else divmod(val,10)
cur.val = val
l1 = l1.next if l1 elseNone
l2 = l2.next if l2 elseNoneif l1 or l2:
cur.next = ListNode(0)
cur = cur.next
if carry:
cur.next = ListNode(carry)
return start