題目描述
解題思路
① 兩個鏈表長度相等
L1:2 -> 4 -> 3
L2:5 -> 6 -> 4
p: 7 -> 0 -> 8
② 兩個鏈表長度不等
L1:2 -> 4 -> 3 -> 6 -> 1
L2:5 -> 6 -> 4
p: 7 -> 0 -> 8 -> 6 -> 1
python代碼
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
p = dummy = ListNode(-1)
carry = 0 # 得到進位值
# carry用來判斷是否進位,p.next.val表示當前值
# l1和l2長度相等時
while l1 and l2:
p.next = ListNode(l1.val + l2.val + carry)
carry = p.next.val // 10
p.next.val %= 10
p = p.next
l1 = l1.next
l2 = l2.next
# l1和l2長度不等時
res = l1 or l2
while res:
p.next = ListNode(res.val + carry)
carry = p.next.val // 10
p.next.val %= 10
p = p.next
res = res.next
# 當carry最後還等於1時,直接進位1
if carry:
p.next = ListNode(1)
return dummy.next
s = Solution()
result = s.addTwoNumbers(l1,l2)
print(result)