面試手撕代碼-leetcode2兩數相加-python

面試手寫代碼!

給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,並且它們的每個節點只能存儲 一位 數字。

如果,我們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。

您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。

示例:

輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807

 

思路:

同時從頭開始遍歷兩個鏈表,如果爲空就假設節點中存的值爲0,不爲空就是其節點本身的值。

結果鏈表中當前節點的值是(tmp1+tmp2+c)%10,對下一位產生的進位爲c = (tmp1+tmp2+c)//10

對於下一個節點的創建:如果【cur1之後還有節點】 或者 【cur2之後都還有節點】 或者 【上一位進位值c>0】,才構造res結果鏈表中的下一個節點。

 

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 and not l2:
            return None
        if not l1 and l2:
            return l2
        if not l2 and l1:
            return l1
        cur1 = l1
        cur2 = l2
        res = ListNode(None)
        head = res
        c = 0   #c表示進位
        while cur1 or cur2:
            # 如果爲空就假設節點中存的值爲0,不爲空就是其節點本身的值
            tmp1 = cur1.val if cur1 else 0
            tmp2 = cur2.val if cur2 else 0
            #計算兩節點值之和存入tmp中
            tmp = tmp1 + tmp2 + c
            res.val = tmp % 10
            c = tmp // 10   #計算向下一位的進位
            #如果cur1之後還有節點 或者 cur2之後都還有節點 或者上一位進位值c>0,才構造res結果鏈表中的下一個節點
            if c > 0  or (cur1 and cur1.next) or (cur2 and cur2.next):
                res.next = ListNode(c)
                res = res.next
            if cur1:
                cur1 = cur1.next
            if cur2:
                cur2 = cur2.next
        return head
if __name__ == '__main__':
    node1 = ListNode(2)
    node2 = ListNode(4)
    node3 = ListNode(3)
    node1.next = node2
    node2.next = node3

    node4 = ListNode(5)
    node5 = ListNode(6)
    node6 = ListNode(9)
    node4.next = node5
    node5.next = node6
    res = Solution().addTwoNumbers(node1,node4)
    while res:
        print(res.val,end=" ")
        res = res.next
    print()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章