Problem: 2. 两数相加
思路 & 解题方法
模拟。
复杂度
时间复杂度:
添加时间复杂度, 示例: O ( n ) O(n) O(n)
空间复杂度:
添加空间复杂度, 示例: O ( n ) O(n) O(n)
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
head = ListNode(0, None)
tail = head
add = 0
while l1 and l2:
sums = l1.val + l2.val + add
# print(l1.val, l2.val, sums, sep = ' ')
add = sums // 10
t = ListNode(sums % 10, None)
tail.next = t
tail = t
l1, l2 = l1.next, l2.next
while l1:
sums = l1.val + add
add = sums // 10
t = ListNode(sums % 10, None)
tail.next = t
tail = t
l1 = l1.next
while l2:
sums = l2.val + add
add = sums // 10
t = ListNode(sums % 10, None)
tail.next = t
tail = t
l2 = l2.next
if add:
t = ListNode(1, None)
tail.next = t
return head.next