面试手撕代码-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()

 

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