题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param head1 ListNode类 # @param head2 ListNode类 # @return ListNode类 # class Solution: def list_reverse(self, head: ListNode) -> ListNode: if head is None: return head pre = None cur = head while cur is not None: post = cur.next cur.next = pre pre = cur cur = post return pre def addInList(self , head1: ListNode, head2: ListNode) -> ListNode: # write code here if head1 is None and head2 is None: return None if head1 is None: return head2 if head2 is None: return head1 head1 = self.list_reverse(head1) head2 = self.list_reverse(head2) carry = 0 head3, p = None, None while head1 is not None or head2 is not None: sum = 0 sum += carry if head1 is not None: sum += head1.val head1 = head1.next if head2 is not None: sum += head2.val head2 = head2.next carry = sum // 10 cur = sum % 10 if head3 is None: head3 = ListNode(cur) p = head3 else: p.next = ListNode(cur) p = p.next if carry > 0: p.next = ListNode(carry) head3 = self.list_reverse(head3) return head3 链表翻转,再从低位开始运算,运算结果再翻转