def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
     if not l1: return l2
     if not l2: return l1
     if l1.val <= l2.val:
         l1.next = self.mergeTwoLists(l1.next, l2)
         return l1
     else:
         l2.next = self.mergeTwoLists(l1, l2.next)
         return l2
 def reverseListNode(self, head: ListNode) -> ListNode:
     if head.next is None:
         return head
     last = self.reverseListNode(head.next)
     head.next.next = head
     head.next = None
     return last
Esempio n. 3
0
 def swapPairs(self, head: ListNode) -> ListNode:
     if not head or not head.next:
         return head
     newHead = head.next
     head.next = self.swapPairs(newHead.next)
     newHead.next = head
     return newHead
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        dummy = ListNode(0)
        dummy.next = head

        pre, end = dummy, dummy

        while end.next:
            # 取出待翻转的部分
            i = 0
            while i < k and end:
                end = end.next
                i += 1
            if not end: break

            # 断开链表
            startNode = pre.next
            nextNode = end.next
            end.next = None

            # 处理翻转
            pre.next = self.reverse(startNode)
            # startNode 转到翻转这部分节点的最后了

            # 连接断开的链表
            startNode.next = nextNode

            # 挪动以进行下一组处理
            pre = startNode
            end = pre
        return dummy.next
Esempio n. 5
0
 def reverseList(self, head: ListNode) -> ListNode:
     if head.next is None:
         return head
     last = self.reverseList(head.next)
     # 环形链表这里vscode没法展示
     head.next.next = head
     head.next = None
     return last
Esempio n. 6
0
 def sortList(self, head: ListNode) -> ListNode:
     res_ls = []
     while head:
         res_ls.append(head.val)
         head = head.next
     if len(res_ls) == 0:
         return
     res_ls.sort()
     node = ListNode(res_ls[0])
     new_head = node
     for i in res_ls[1:]:
         node.next = ListNode(i)
         node = node.next
     return new_head