题目:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
python解法一:
def addTwoNumbers(self, l1, l2):
res = cur = ListNode(0)
while l1 or l2 :
# print(l1,l2)
if l1 is None:
l1 = ListNode(0)
if l2 is None:
l2 = ListNode(0)
if l1.val+l2.val>=10 :
cur.next = ListNode(l1.val+l2.val-10)
if l1.next and l2.next :
l1.next.val += 1
elif l1.next and l2.next is None :
l2.next = ListNode(1)
elif l2.next and l1.next is None :
l1.next = ListNode(1)
else:
l1.next = ListNode(0)
l2.next = ListNode(1)
else :
cur.next = ListNode(l1.val+l2.val)
l1 = l1.next
l2 = l2.next
cur = cur.next
return res.next