牛客 NC40 链表相加(二)

class Solution:
    jinwei = 0
    def researve(self, first, second):
        while second is not None:
            tmp = second.next
            second.next = first
            first = second
            second = tmp
        return first
    def cosum(self, head, jinwei, l3):
        val = head.val+jinwei       
        if val > 9:
            val = val - 10
            tmp = ListNode(val)
            l3.next = tmp
            l3 = l3.next
            tmp = ListNode(1)
            l3.next = tmp
        else:
            self.jinwei = 0
            tmp = ListNode(val)
            l3.next = tmp
        return l3

    def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
        # write code here
        l1 = self.researve(None, head1)
        l2 = self.researve(None, head2)

        l3 = ListNode(-1)
        res = l3
        while l1 is not None and l2 is not None:
            val = l1.val + l2.val + self.jinwei
            if val > 9:
                val = val - 10
                self.jinwei = 1
            else:
                self.jinwei = 0
            tmp = ListNode(val)
            l3.next = tmp
            l3 = l3.next
            l1 = l1.next
            l2 = l2.next

        if l1 is None and l2 is None and self.jinwei == 1:
            tmp = ListNode(self.jinwei)
            l3.next = tmp

        while l1 is not None:
            self.cosum(l1, self.jinwei, l3)
            l1 = l1.next
            l3 = l3.next
        while l2 is not None:
            self.cosum(l2, self.jinwei, l3)
            l2 = l2.next
            l3 = l3.next
        result = self.researve(None, res.next)

        return result

先反转链表:

    def researve(self, first, second):
        while second is not None:
            tmp = second.next
            second.next = first
            first = second
            second = tmp
        return first

用这个,把两个链表反转,然后对应节点相加,注意进位,然后结果再反转回来

对应位置相加的代码:

    def cosum(self, head, jinwei, l3):
        val = head.val+jinwei       
        if val > 9:
            val = val - 10
            # self.jinwei = 1
            tmp = ListNode(val)
            l3.next = tmp
            l3 = l3.next
            tmp = ListNode(1)
            l3.next = tmp
        else:
            self.jinwei = 0
            tmp = ListNode(val)
            l3.next = tmp
        while l1 is not None and l2 is not None:
            val = l1.val + l2.val + self.jinwei
            if val > 9:
                val = val - 10
                self.jinwei = 1
            else:
                self.jinwei = 0
            tmp = ListNode(val)
            l3.next = tmp
            l3 = l3.next
            l1 = l1.next
            l2 = l2.next

第一段是当另一段链表用完时的加法,第二段是两段链表相加的代码,难点还是在于进位

又慢又大,除了我能看懂之外没有优点了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值