简单易懂

两个链表生成相加链表

http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

  • 首先反转需要相加的两个链表
  • 其次每次新建节点tmp,把tmp.next -> res; 然后res = tmp
class Solution:
    def reverseList(self, head):
        res = None
        cur = head
        while cur:
            tmp = cur.next
            cur.next = res
            res = cur 
            cur = tmp
        return res

    def addInList(self, head1, head2):
        # write code here
        rhead1 = self.reverseList(head1)
        rhead2 = self.reverseList(head2)
        rp1, rp2 = rhead1, rhead2
        carry = 0
        res = None
        while rp1 or rp2:
            val1 = rp1.val if rp1 is not None else 0
            val2 = rp2.val if rp2 is not None else 0
            carry, val = divmod(val1 + val2 + carry, 10)
            tmp = ListNode(val)
            tmp.next = res
            res = tmp
            if rp1:
                rp1 = rp1.next
            if rp2:
                rp2 = rp2.next

        if carry > 0:
            tmp = ListNode(carry)
            tmp.next = res
            res = tmp
        return res
全部评论

相关推荐

10-30 10:16
南京大学 Java
龚至诚:给南大✌️跪了
点赞 评论 收藏
分享
双非坐过牢:非佬,可以啊10.28笔试,11.06评估11.11,11.12两面,11.19oc➕offer
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务