while tail and tail.next and count < k:
                count += 1
                tail = tail.next
            if count != k:
                break

            node = head
            next = node.next
            for i in range(k-1):
                tmp = next.next
                next.next = node
                node = next
                next = tmp

            if not prev:
                newhead = tail
            else:
                prev.next = tail
            prev = head
            head.next = tmp
            head = tmp
            tail = head

        if not newhead:
            newhead = head
        return newhead

a = ListNode.from_list([1,2,3,4,5,6])
s = Solution()
print(s.reverseKGroup(a, 2))
    # @return a tree node
    def sortedListToBST(self, head):
        if not head:
            return None
        if not head.next:
            node = TreeNode(head.val)
            return node

        fast = head
        slow = head
        prev = None
        while fast.next and fast.next.next:
            fast = fast.next.next
            prev = slow
            slow = slow.next

        node = TreeNode(slow.val)
        right = slow.next
        if prev:
            prev.next = None
            node.left = self.sortedListToBST(head)
        else:
            node.left = self.sortedListToBST(None)
        node.right = self.sortedListToBST(right)
        return node

a = [1,2,3,4]
l = ListNode.from_list(a)
s = Solution()
print(s.sortedListToBST(l))
Exemple #3
0
    def rotateRight(self, head, k):
        if not head or k <= 0:
            return head

        num = 0
        node = head
        while node:
            node = node.next
            num += 1
        k = k % num
        if k == 0:
            return head

        fast = head
        for i in range(k):
            fast = fast.next
        slow = head

        while fast.next:
            slow = slow.next
            fast = fast.next

        fast.next = head
        head = slow.next
        slow.next = None
        return head

node = ListNode.from_list([1])
s = Solution()
print(s.rotateRight(node, 1))
        head = None
        curr = None
        while nodes:
            n = len(nodes)
            minv = float('inf')
            index = 0
            for i in range(n):
                node = nodes[i]
                if node.val < minv:
                    minv = node.val
                    index = i

            if not head:
                head = ListNode(minv)
                curr = head
            else:
                curr.next = ListNode(minv)
                curr = curr.next

            node = nodes[index].next
            if not node:
                nodes.pop(index)
            else:
                nodes[index] = node
        return head

a = ListNode.from_list([1,2,3])
b = ListNode.from_list([2,3,4])
s = Solution()
print(s.mergeKLists([a,b]))