python;leetcode 两数相加

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """

        dummy = cur = ListNode(0) #链表节点头,方便后续操作
        carry = 0
        while l1 or l2 or carry: #l1,l2,carry不都为0的时候进行循环操作
            if l1:
                carry += l1.val #carry加上l1的值
                l1 = l1.next    #l1挪动到下一位
            if l2:
                carry += l2.val  #类似累加
                l2 = l2.next
            cur.next = ListNode(carry%10) #取余
            cur = cur.next  #挪动节点
            carry //= 10  # carry = carry//10
        return dummy.next

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页