# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defreverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: ifnot head ornot head.nextor left == right: return head pre = None cur = head for _ inrange(left - 1): pre = cur cur = cur.next
l1 = pre tail_l2 = cur
for _ inrange(right - left + 1): tmp = cur.next cur.next = pre pre = cur cur = tmp
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defaddTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: defreverse_list(lst): head = lst pre, cur = None, head while cur: tmp = cur.next cur.next = pre pre = cur cur = tmp return pre
l1, l2 = reverse_list(l1), reverse_list(l2)
carry = 0
l3 = ListNode(0) cur = l3
while l1 or l2 or carry: value = (l1.val if l1 else0) + (l2.val if l2 else0) + carry carry, number = divmod(value, 10) cur.next = ListNode(number) cur = cur.next l1 = l1.nextif l1 elseNone l2 = l2.nextif l2 elseNone