1.題目描述:
給出兩個 非空 的鏈表用來表示兩個非負的整數(shù)尚揣。其中涌矢,它們各自的位數(shù)是按照 逆序 的方式存儲的,并且它們的每個節(jié)點只能存儲 一位 數(shù)字快骗。如果娜庇,我們將這兩個數(shù)相加起來,則會返回一個新的鏈表來表示它們的和方篮。
您可以假設(shè)除了數(shù)字 0 之外名秀,這兩個數(shù)都不會以 0 開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
2.分析
這個問題首先是一個鏈表問題藕溅,取出每個鏈表中的每一個節(jié)點進行相加匕得,需要用一個變量去承接進位值◎诳澹考慮的邊界條件有兩個,一個是兩個鏈表的長度不一致裕照,另一個是最后兩個節(jié)點相加完有進位值攒发。
3.解決
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
add = 0 # 設(shè)定增加的值為0
head = ListNode(0) # 先設(shè)定一個頭節(jié)點
node = head # 設(shè)置當前節(jié)點
while l1 or l2: # 循環(huán)結(jié)束條件為l1 且 l2 已經(jīng)沒有下一個節(jié)點了
cur = ListNode(add) # 生成一個節(jié)點
if l1:
cur.val += l1.val # 當l1有節(jié)點的情況,增加值
l1 = l1.next # l1 取到下一個節(jié)點
if l2:
cur.val += l2.val
l2 = l2.next
add = cur.val // 10 # 取除完10的余數(shù)
cur.val = cur.val % 10 # 取對10取的商值
node.next, node = cur, cur # 變換節(jié)點
if add:
node.next = ListNode(add)
return head.next