两数相加II-链表445

Python

没看答案。

  1. 先将两个链表反转;
  2. 按照leetcode第2题两数相加的方法相加两个链表;
  3. 将相加后的链表反转,得到输出。
# 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同上。

猜你喜欢

转载自blog.csdn.net/VaccyZhu/article/details/113809827