题目:
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.
思路:
这题有两种思路:第一是将两个列表的数字整合成两个整数相加之后再转换成列表,这种方法在列表所表示的数字比较小的时候是可行的,一旦数字过大就会出现溢出问题(我使用这种方法的时候1562个例子过了1560个,剩下两个都是因为数字过大);因此要使用逐位相加的方法,在python里面非常容易实现,只要注意一下位相加即可。
代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
if l1 == None or l2 == None:
if l1 == None:
return l2
elif l2 == None:
return l1
left = 0 #进位
ans = ListNode(0)
p = ListNode(0)
p = ans #将p指向ans,ans指针不移动而p移动
while l1 != None or l2 != None:
if l1 == None:
if l2.val + left >= 10:
temp = (l2.val + left) % 10
left = 1
p.next = ListNode(temp)
p = p.next
l2 = l2.next
continue
else:
temp = l2.val + left
left = 0
p.next = ListNode(temp)
p = p.next
l2 = l2.next
continue
elif l2 == None:
if l1.val + left >= 10:
temp = (l1.val + left) % 10
left = 1
p.next = ListNode(temp)
p = p.next
l1 = l1.next
continue
else:
temp = l1.val + left
left = 0
p.next = ListNode(temp)
p = p.next
l1 = l1.next
continue
else:
if l1.val + l2.val + left >= 10:
temp = (l1.val + l2.val + left) % 10
left = 1
p.next = ListNode(temp)
p = p.next
l1 = l1.next
l2 = l2.next
continue
else:
temp = l1.val + l2.val + left
left = 0
p.next = ListNode(temp)
p = p.next
l1 = l1.next
l2 = l2.next
continue
if left == 1: #不要忘了最后一位
p.next = ListNode(1)
return ans.next #因为是从p的下一位开始赋值的,所以返回ans的下一位