题解 | #链表相加(二)#

链表相加(二)

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

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head1 ListNode类
# @param head2 ListNode类
# @return ListNode类
#
class Solution:
    def addInList(self, head1: ListNode, head2: ListNode) -> ListNode:
        # write code here
        # 反转链表1,2
        pre = None
        cur = head1
        while cur:
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp
        reverse_head1 = pre

        pre = None
        cur = head2
        while cur:
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp
        reverse_head2 = pre

        # 从个位开始诸位详加,并记录进位add
        add = 0
        dummy_head = ListNode(-1)
        cur = dummy_head
        rp1, rp2 = reverse_head1, reverse_head2
        while rp1 or rp2 or add:
            val1 = rp1.val if rp1 else 0
            val2 = rp2.val if rp2 else 0
            result = add + val1 + val2
            add, val = divmod(result, 10)
            # rp1, rp2 = rp1.next, rp2.next
            if rp1:
                rp1 = rp1.next
            if rp2:
                rp2 = rp2.next
            node = ListNode(val)
            cur.next = node
            cur = cur.next

        # 反转结果链表
        pre = None
        cur = dummy_head.next
        while cur:
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp

        return pre

整体思路很好理解:

  1. 首先反转链表1,2
  2. 然后诸位相加,并记录进位
  3. 最后反转结果链表返回即可

这里翻转链表直接背过模板即可。

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务