給定兩個非空鍊錶來代表兩個非負整數。數字最高位位於鍊錶開始位置。它們的每個節點只儲存單個數字。將這兩數相加會返回乙個新的鍊錶。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
高階:
如果輸入鍊錶不能修改該如何處理?換句話說,你不能對列表中的節點進行翻轉。
示例:
輸入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出: 7 -> 8 -> 0 -> 7
用棧分別儲存2個列表的值,再按位相加
時間》40.53%
空間》11.11%
# definition for singly-linked list.
# class listnode(object):
# def __init__(self, x):
# self.val = x
# self.next = none
class
solution
(object):
defaddtwonumbers
(self, l1, l2)
:"""
:type l1: listnode
:type l2: listnode
:rtype: listnode
"""stack1, stack2 =
,[] p = l1
while p:
p = p.
next
p = l2
while p:
p = p.
next
ret_head =
none
carry =
0while stack1 and stack2:
a, b = stack1.pop(
), stack2.pop(
) val =
(a + b + carry)%10
carry =
(a + b + carry)
//10
node = listnode(val)
node.
next
= ret_head
ret_head = node
while stack1:
e = stack1.pop(
) val =
(e + carry)%10
carry =
(e + carry)
//10
node = listnode(val)
node.
next
= ret_head
ret_head = node
while stack2:
e = stack2.pop(
) val =
(e + carry)%10
carry =
(e + carry)
//10
node = listnode(val)
node.
next
= ret_head
ret_head = node
if carry:
node = listnode(carry)
node.
next
= ret_head
ret_head = node
return ret_head
leetcode 445 兩數相加 II
給定兩個非空鍊錶來代表兩個非負整數。數字最高位位於鍊錶開始位置。它們的每個節點只儲存單個數字。將這兩數相加會返回乙個新的鍊錶。你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。輸入 7 2 4 3 5 6 4 輸出 7 8 0 7 分別遍歷兩個鍊錶,將鍊錶代表的數存於a,b 根據a,b的和,用...
Leetcode445 兩數相加 II
給定兩個非空鍊錶來代表兩個非負整數。數字最高位位於鍊錶開始位置。它們的每個節點只儲存單個數字。將這兩數相加會返回乙個新的鍊錶。你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。高階 如果輸入鍊錶不能修改該如何處理?換句話說,你不能對列表中的節點進行翻轉。示例 輸入 7 2 4 3 5 6 4 ...
LeetCode 445 兩數相加II(Java)
給定兩個非空鍊錶來代表兩個非負整數。數字最高位位於鍊錶開始位置。它們的每個節點只儲存單個數字。將這兩數相加會返回乙個新的鍊錶。你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。高階 鍊錶不能修改該,換句話說,你不能對列表中的節點進行翻轉。示例 輸入 7 2 4 3 5 6 4 輸出 7 8 0...