題目出處
來自于leetcode
題目描述
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
解讀
給定兩個表示兩個非負整數(shù)的單鏈表俱箱,這兩個數(shù)按反序保存在單鏈表中迈套,把兩個數(shù)相加并返回一個單鏈表集峦。
給定的例子為342 + 465 = 807
第一版答案
- 從兩個單鏈表的開頭相加员帮,記住進位藐吮;
- 幾個邊界條件需要注意:
- 入?yún)⒌膬蓚€單鏈表有可能為空呼猪,若一個為空辞州,則直接返回另一個即可怔锌;
- 兩個單鏈表長度可能不一樣,在相加結(jié)束后需要把比較長的剩余的數(shù)值拷貝過去孙技;
- 進位也需要考慮产禾,如5 + 5 = 10, 當(dāng)兩個單鏈表處理完畢后牵啦,如果還有進位亚情,還需要增加一個節(jié)點
代碼如下
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2
if not l2:
return l1
carry = 0
sums = l1.val + l2.val + carry
carry = sums / 10
res = ListNode(sums % 10)
l1 = l1.next
l2 = l2.next
node = res
while l1 and l2:
sums = l1.val + l2.val + carry
tmp = ListNode(sums % 10)
carry = sums / 10
node.next = tmp
node = node.next
l1 = l1.next
l2 = l2.next
while l1:
sums = l1.val + carry
tmp = ListNode(sums % 10)
carry = sums / 10
node.next = tmp
node = node.next
l1 = l1.next
while l2:
sums = l2.val + carry
tmp = ListNode(sums % 10)
carry = sums / 10
node.next = tmp
node = node.next
l2 = l2.next
while carry:
tmp = ListNode(carry % 10)
carry = carry / 10
node.next = tmp
node = node.next
return res
第二版答案
第一版答案中的代碼不夠精煉,從以下兩個地方入手:
- 入?yún)⑴袛喙瑢1和l2的檢查上楞件,先定義一個頭節(jié)點,返回頭節(jié)點的next裳瘪,這樣可以避免處理l1或l2為空的情形土浸,將鏈表中所有的節(jié)點一視同仁進行處理;
- 將四個while語句合并處理
代碼如下:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
carry = 0
node = head
while l1 or l2 or carry:
val1, val2 = 0, 0
if l1:
val1 = l1.val
l1 = l1.next
if l2:
val2 = l2.val
l2 = l2.next
sums = val1 + val2 + carry
tmp = ListNode(sums % 10)
carry = sums / 10
node.next = tmp
node = node.next
return head.next
代碼簡潔了許多彭羹,由于增加了比較多的比較黄伊,效率會稍微下降點。