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 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 reverseKGroup(self, head: ListNode, k: int) -> ListNode: count = 0 ltmp: ListNode = head while count < k and ltmp: ltmp = ltmp.next count += 1 if count < k: return head cur: ListNode = self.reverseKGroup(ltmp, k) while count > 0: ltmp = head.next head.next = cur cur = head head = ltmp count -= 1 return cur