给定两个非空列表用来表示两个正整数,给定的数以反序存储在链表中,链表中每个节点的值表示一位数,将两个数字求和并以链表形式返回
可以假定除0外,所有给定的数字都不包含前导0
例:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.解法1(理解较容易):
# 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:
list1 = []
list2 = []
while l1:
list1.insert(0, l1.val)
l1 = l1.next
while l2:
list2.insert(0, l2.val)
l2 = l2.next
result = int(''.join(map(str, list1))) + int(''.join(map(str, list2)))
s = str(result)
k = None
for i in range(len(s)):
node = ListNode(int(s[i]))
node.next = k
k = node
return k解法2(pythonic,性能更高)
# 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:
head = ListNode(0)
tail = head
carry = 0
while l1 or l2 or carry:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
carry, val = divmod(val1 + val2 + carry, 10)
tail.next = ListNode(val)
tail = tail.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return head.next