You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up: What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defaddTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: defreverse_node(l): ifnot l ornot l.next: return l pre = None while l: tmp = l.next l.next = pre pre = l l = tmp return pre res = point = ListNode(0) extra = 0 l1 = reverse_node(l1) l2 = reverse_node(l2)
while l1 != Noneor l2 != None: l1_ele = l1.val if l1 != Noneelse0 l2_ele = l2.val if l2 != Noneelse0 sum = l1_ele + l2_ele + extra extra = 1ifsum >= 10else0 point.next = ListNode(int(sum%10)) point = point.next if l1 != None: l1 = l1.next if l2 != None: l2 = l2.next
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None
classSolution(object): defaddTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ stack1 = [] stack2 = [] while l1: stack1.append(l1.val) l1 = l1.next while l2: stack2.append(l2.val) l2 = l2.next res = ListNode() extra = 0 while stack1 and stack2: sum = stack1.pop() + stack2.pop() + extra extra = 1ifsum >= 10else0 tmp = res res = ListNode(int(sum % 10)) res.next = tmp l = stack1 if stack1 else stack2 while l: sum = l.pop() + extra extra = 1ifsum >= 10else0 tmp = res res = ListNode(int(sum % 10)) res.next = tmp if extra: tmp = res res = ListNode(1) res.next = tmp return res.next