題目描述
給出兩個 非空 的連結串列用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式儲存的,並且它們的每個節點只能儲存 一位 數字。
如果,我們將這兩個數相加起來,則會返回一個新的連結串列來表示它們的和。
您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
複製程式碼
解決:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
p = l1
q = l2
carry = 0
result = ListNode(0)
curr = result
while (p != None or q != None):
x = p.val if(p != None) else 0
y = q.val if(q != None) else 0
sum = x + y + carry
carry = sum // 10
curr.next = ListNode(sum % 10)
curr = curr.next
if p != None:
p = p.next
if q != None:
q = q.next
if (carry > 0):
curr.next = ListNode(carry)
return result.next
複製程式碼
若連結串列中的數字按正序儲存的;解決方法:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
# 連結串列中的數字按正序儲存的
m = l1
n = l2
len1 = self.getLenth(l1)
len2 = self.getLenth(l2)
#將 m 賦為長度短的連結串列, n 為長度較長的連結串列
m = l1 if len1 <= len2 else l2
n = l1 if len2 <= len1 else l2
# 對長度短的連結串列m,前面進行 補0 操作
for i in range(self.getLenth(m), self.getLenth(n)):
cur = ListNode(0)
cur.next = m
m = cur
result = self.add(m, n)
if result.val == 0:
return result.next
else:
return result
def getLenth(self,ln):
count = 0
while(ln != None):
count += 1
ln = ln.next
return count
def add(self, p1, p2):
add_result = ListNode(0)
if (p1.next == None):
num = p1.val + p2.val
sum = ListNode(num)
if num > 9:
add_result.val += 1
sum.val -= 10
add_result.next = sum
return add_result
else:
a = self.add(p1.next, p2.next)
num = p1.val + p2.val + a.val
sum = ListNode(num)
sum.next = a.next
if num > 9:
add_result.val += 1
sum.val -= 10
add_result.next = sum
return add_result
複製程式碼