def splitListToParts(self, head: Optional[ListNode],
                         k: int) -> List[Optional[ListNode]]:
        ans: List[ListNode] = []
        cur = head
        allcount = 0
        while cur:
            allcount += 1
            cur = cur.next

        eachcount = allcount // k
        remainder = allcount - eachcount * k

        cur = ListNode(0)
        cur.next = head
        for i in range(k):
            if eachcount + remainder == 0:
                ans.append(None)
            else:
                tmp = eachcount
                while cur.next and tmp > 0:
                    cur = cur.next
                    tmp -= 1
                if remainder > 0:
                    if cur.next:
                        cur = cur.next
                    remainder -= 1

                temp = cur.next
                cur.next = None
                ans.append(head)
                head = temp
                cur = ListNode(0)
                cur.next = head  # ensure cur is the tail element

        return ans
    def addTwoNumbers(self, l1: Optional[ListNode],
                      l2: Optional[ListNode]) -> Optional[ListNode]:
        prev = ListNode(0)
        cur = prev
        carry = 0
        while l1 or l2:
            v1 = l1.val if l1 else 0
            v2 = l2.val if l2 else 0
            v = v1 + v2 + carry
            v0 = v % 10
            carry = v // 10
            tmp = ListNode(v0)
            cur.next = tmp
            cur = cur.next

            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None

        if carry > 0:
            tmp = ListNode(carry)
            cur.next = tmp

        return prev.next
Example #3
0
        def mergeList(l1: ListNode, l2: ListNode) -> ListNode:
            tmp = ListNode(0)
            sortlist = tmp
            while l1 and l2:
                if l1.val < l2.val:
                    tmp.next = l1
                    l1 = l1.next
                    tmp = tmp.next
                else:
                    tmp.next = l2
                    l2 = l2.next
                    tmp = tmp.next
            if l1:
                tmp.next = l1
            elif l2:
                tmp.next = l2

            return sortlist.next
        def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
            lret = ListNode(0)
            ll, lr = l1, l2
            lptr = lret
            while ll and lr:
                if ll.val <= lr.val:
                    lptr.next = ll
                    ll = ll.next
                else:
                    lptr.next = lr
                    lr = lr.next
                lptr = lptr.next

            if ll:
                lptr.next = ll
            else:
                lptr.next = lr

            return lret.next