你有兩個用鏈表代表的整數(shù),其中每個節(jié)點(diǎn)包含一個數(shù)字。數(shù)字存儲按照在原來整數(shù)中相反的順序,使得第一個數(shù)字位于鏈表的開頭。寫出一個函數(shù)將兩個整數(shù)相加,用鏈表形式返回和。
您在真實(shí)的面試中是否遇到過這個題?
樣例
給出兩個鏈表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null
"""
Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
"""
class Solution:
"""
@param: l1: the first list
@param: l2: the second list
@return: the sum list of l1 and l2
"""
def addLists(self, l1, l2):
# write your code here
if l1 is None and l2 is None:
return None
cur1 = l1.next
cur2 = l2.next
head = ListNode((l1.val + l2.val)%10)
cur = head
carry = (l1.val + l2.val) // 10
#當(dāng)其中一條鏈表為空的時候,為該鏈表添加一個值為0的節(jié)點(diǎn)
#直到兩條都為None,這種方式會修改原先的列表.
while cur1 is not None or cur2 is not None:
if cur1 is None:cur1 = ListNode(0)
if cur2 is None:cur2 = ListNode(0)
val = cur1.val + cur2.val + carry
carry = val // 10
cur.next = ListNode(val%10)
cur = cur.next
cur1 = cur1.next
cur2 = cur2.next
if carry != 0:
cur.next = ListNode(carry)
return head