題目描述:
給定兩個(gè)鏈表弹谁,輸出兩個(gè)鏈表的和聪姿,具體形式如下:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
解題思路:
首先分別計(jì)算出每個(gè)鏈表的數(shù)字(342 and 465)芽隆,然后在進(jìn)行相加炫隶,把相加后的每一位存放進(jìn)新的鏈表中洞辣。最后處理一下最高進(jìn)位叉存。python 代碼如下:
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
rest = ListNode(0)
ans = rest
suml = 0
i = 1
while l1 != None:
suml += l1.val * i
l1 = l1.next
i *= 10
i = 1
while l2 != None:
suml += l2.val * i
l2 = l2.next
i *= 10
while suml != 0:
ans.val = suml % 10
suml /= 10
if suml != 0:
ans.next = ListNode(0)
ans = ans.next
return rest