你有兩個(gè)用鏈表代表的整數(shù)垃杖,其中每個(gè)節(jié)點(diǎn)包含一個(gè)數(shù)字胎许。數(shù)字存儲(chǔ)按照在原來(lái)整數(shù)中相反的順序奈辰,使得第一個(gè)數(shù)字位于鏈表的開(kāi)頭栏妖。寫(xiě)出一個(gè)函數(shù)將兩個(gè)整數(shù)相加,用鏈表形式返回和奖恰。
您在真實(shí)的面試中是否遇到過(guò)這個(gè)題吊趾?
樣例
給出兩個(gè)鏈表 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)其中一條鏈表為空的時(shí)候,為該鏈表添加一個(gè)值為0的節(jié)點(diǎn)
#直到兩條都為None,這種方式會(huì)修改原先的列表.
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