兩個(gè)用鏈表代表的整數(shù),其中每個(gè)節(jié)點(diǎn)包含一個(gè)數(shù)字。數(shù)字存儲按照在原來整數(shù)中相反的順序砰盐,使得第一個(gè)數(shù)字位于鏈表的開頭。寫出一個(gè)函數(shù)將兩個(gè)整數(shù)相加杆融,用鏈表形式返回和楞卡。
樣例:
輸入
3->1->5->null
5->9->2->null
輸出
8->0->8->null
解決方案
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
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:
return l2
elif l2 is None:
return l1
else:
flag = False
result = ListNode(0)
tmp = l1.val + l2.val
if flag:
tmp += 1
flag = False
if tmp >= 10:
flag = True
tmp = tmp - 10
result.val = tmp
result.next = ListNode(0)
cycle = result
l1=l1.next
l2=l2.next
while(l1 is not None and l2 is not None):
cycle = cycle.next
tmp = l1.val + l2.val
if flag:
tmp += 1
flag = False
if tmp >= 10:
flag = True
tmp = tmp - 10
cycle.val = tmp
cycle.next = ListNode(0)
l1=l1.next
l2=l2.next
if l1 is None and l2 is None:
if flag:
cycle = cycle.next
cycle.val = 1
cycle.next = None
flag = False
else:
cycle.next = None
else:
final = l1 if l1 is not None else l2
while(final is not None):
cycle = cycle.next
if flag:
cycle.val = final.val + 1
if cycle.val >= 10:
cycle.val -= 10
else:
flag = False
else:
cycle.val = final.val
cycle.next = ListNode(0)
final = final.next
if flag:
cycle = cycle.next
cycle.val = 1
cycle.next = None
else:
cycle.next = None
return result
思路:
兩個(gè)鏈表按位相加,關(guān)鍵問題是要注意越界的問題和進(jìn)位的問題