Python
没看答案。
- 先将两个链表反转;
- 按照leetcode第2题两数相加的方法相加两个链表;
- 将相加后的链表反转,得到输出。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
l1 = self.ReverseLinkedList(l1)
l2 = self.ReverseLinkedList(l2)
carry, val = 0, 0
curr = head = ListNode(100)
while l1 or l2 or carry:
val = carry
if l1:
val += l1.val
l1 = l1.next
if l2:
val += l2.val
l2 = l2.next
carry, val = divmod(val,10)
curr.next = ListNode(val)
curr = curr.next
return self.ReverseLinkedList(head.next)
def ReverseLinkedList(self, head):
pre = None
while(head):
temp = head.next
head.next = pre
pre = head
head = temp
return pre
复杂度分析:
- 时间复杂度:O(m+n),其中m和n分别为l1和l2的元素个数。
- 空间复杂度:O(m+n),m和n同上。