def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or not head.next or k <= 1:
            #return head
            return LinkedList(head).values()

        dummy = ListNode(None)
        dummy.next = head
        gprev = dummy
        while gprev.next:
            tmp = gprev
            for i in xrange(k):
                tmp = tmp.next
                if not tmp:
                    #return dummy.next
                    return LinkedList(dummy.next).values()
            gtail, pc = gprev.next, gprev.next.next
            for i in xrange(k - 1):
                gprev.next, pc.next, gtail.next = pc, gprev.next, pc.next
                pc = gtail.next
            gprev = gtail
        #return dummy.next
        return LinkedList(dummy.next).values()
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        head_values = sorted([(p, p.val) for p in lists if p],
                             key=lambda x: x[1],
                             reverse=True)
        if not head_values:
            return None

        dummy = ListNode(None)
        curr = dummy
        while len(head_values) > 1:
            if head_values[-1][1] <= head_values[-2][1]:
                curr.next = head_values[-1][0]
                curr = curr.next
                if head_values[-1][0].next:
                    head_values[-1] = (head_values[-1][0].next,
                                       head_values[-1][0].next.val)
                else:
                    head_values.pop()
            else:
                head_values.sort(key=lambda x: x[1], reverse=True)

        curr.next = head_values[0][0]
        #return dummy.next
        return LinkedList(dummy.next).values()
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        def mergetwo(l1, l2):
            dummy = ListNode(None)
            curr = dummy
            while l1 and l2:
                if l1.val <= l2.val:
                    curr.next, l1 = l1, l1.next
                else:
                    curr.next, l2 = l2, l2.next
                curr = curr.next

            if not l1:
                curr.next = l2
            else:
                curr.next = l1
            return dummy.next

        #print 'here'
        if not list:
            return None
        while len(lists) > 1:
            #print 'here'
            newhead = mergetwo(lists.pop(), lists.pop())
            #print newhead.val
            lists.append(newhead)
        #return lists[0]
        return LinkedList(lists[0]).values()
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            #return head
            return None if not head else [head.val]

        dummy = ListNode(None)
        dummy.next = head
        prev, left, right = dummy, head, head.next
        while left and right:
            pnext = right.next
            prev.next, right.next, left.next = right, left, right.next
            prev, left = left, pnext
            right = left.next if left else None
        #return dummy.next
        return LinkedList(dummy.next).values()
 def mergeKLists(self, lists):
     """
     :type lists: List[ListNode]
     :rtype: ListNode
     """
     lists = [p for p in lists if p]
     if not lists:
         return None
     values = [p.val for p in lists]
     dummy = ListNode(None)
     curr = dummy
     while len(lists) > 1:
         ind = values.index(min(values))
         curr.next = lists[ind]
         curr = curr.next
         if not lists[ind].next:
             lists.pop(ind)
             values.pop(ind)
         else:
             lists[ind] = lists[ind].next
             values[ind] = lists[ind].val
     curr.next = lists[0]
     #return dummy.next
     return LinkedList(dummy.next).values()
        while left and right:
            pnext = right.next
            prev.next, right.next, left.next = right, left, right.next
            prev, left = left, pnext
            right = left.next if left else None
        #return dummy.next
        return LinkedList(dummy.next).values()


class Solution2(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        dummy = ListNode(None)
        dummy.next = head
        prev = dummy
        while prev.next and prev.next.next:
            first, second = prev.next, prev.next.next
            prev.next, second.next, first.next = second, first, second.next
            prev = first
        return dummy.next


if __name__ == "__main__":
    from leetcodelib import test
    num_lists = [[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
    arguments = [LinkedList(nums).head for nums in num_lists]
    answers = [None, [0], [1, 0], [1, 0, 2], [1, 0, 3, 2]]
    test(Solution2().swapPairs, arguments, answers)
Пример #7
0
        if not head or not head.next or not head.next.next:
            return head

        slow, fast = head, head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next

        prev, curr = None, slow.next
        slow.next = None
        while curr:
            curr.next, prev, curr = prev, curr, curr.next

        node, next_node = head, prev
        while node:
            print node, next_node
            node.next, node, next_node = next_node, next_node, node.next
        return head


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    nums = [range(x) for x in xrange(1, 6)]
    arguments = [LinkedList(x).head for x in nums]
    answers = [[0], [0, 1], [0, 2, 1], [0, 3, 1, 2], [0, 4, 1, 3, 2]]
    test(Solution().reorderList, arguments, answers, inds=[3])

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
Пример #8
0
 def func1(self, nums):
     linkedlist = LinkedList(nums)
     return linkedlist.head
Пример #9
0
        """
        small = dummy_small = ListNode(None)
        large = dummy_large = ListNode(None)

        node = head
        while node:
            if node.val < x:
                small.next = node
                small = small.next
            else:
                large.next = node
                large = large.next
            node = node.next

        small.next = dummy_large.next
        large.next = None
        return dummy_small.next


if __name__ == "__main__":
    import numpy as np
    numbers, x = np.random.randint(10, size=20), 5
    #numbers, x = [5] * 20, 5
    #numbers, x = [4] * 20, 5
    #numbers, x = [2, 1], 3
    testlist = LinkedList(numbers)
    testlist.write()

    head = Solution().partition(testlist.head, x)
    LinkedList().write(head)
            else:
                curr.next, l2 = l2, l2.next
            curr = curr.next

        if not l1:
            curr.next = l2
        else:
            curr.next = l1
        return dummy.next


if __name__ == "__main__":
    from leetcodelib import LinkedList
    from random import sample
    nums1 = sorted(sample(range(100), 10))
    list1 = LinkedList(nums1)
    list1.write()

    nums2 = sorted(sample(range(100), 10))
    list2 = LinkedList(nums2)
    list2.write()

    nums_new = sorted(nums1 + nums2)
    list_new = LinkedList(nums_new)
    list_new.write()

    answer = LinkedList(nums_new).values()
    head_new = Solution().mergeTwoLists(list1.head, list2.head)
    result = LinkedList(head_new).values()

    print answer
if __name__ == "__main__":
    from leetcodelib import test, update_testfile, load_testfile
    from random import sample, randint
    import yaml

    testfile = __file__.replace('.py', '.yaml')

    def add_new_testcases():
        arg_names = 'num_lists'
        k = randint(1, 20)
        args = [sorted(sample(range(100), randint(1, 10))) for _ in xrange(k)]
        answer = sorted([x for l in args for x in l])
        update_testfile(testfile, arg_names, [args], [answer])

    arg_orders, arguments, answers = load_testfile(testfile)
    #arguments = [[[], []]]
    #answers = [None]

    #print len(arguments), len(answers)
    #print arguments[-1][0]
    #arguments = [([LinkedList(x).head for x in args[0]],) for args in arguments]
    #print arguments[-1][0]

    #test(Solution1().mergeKLists, [([LinkedList(x).head for x in args[0]],) for args in arguments], answers)
    #test(Solution2().mergeKLists, [([LinkedList(x).head for x in args[0]],) for args in arguments], answers)
    #test(Solution3().mergeKLists, [([LinkedList(x).head for x in args[0]],) for args in arguments], answers)
    test(Solution4().mergeKLists,
         [([LinkedList(x).head for x in args[0]], ) for args in arguments],
         answers,
         inds=[])
Пример #12
0
        
        revprev, revhead = prev, curr
        prev, curr = curr, curr.next
        
        for _ in xrange(n-m):
            curr.next, prev, curr = prev, curr, curr.next

        revhead.next = curr
        revprev.next = prev
        return dummy.next
        

if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    from random import sample
    
    def verify(nums, m, n):
        m -= 1
        n -= 1
        return nums[:m] + nums[n:m-1:-1] + nums[n+1:]

    l = sample(range(100), 20)
    print l
    arguments = [(LinkedList(l).head, 3, 15)]
    answers = [verify(l, x[1], x[2]) for x in arguments]
    test(Solution().reverseBetween, arguments, answers)
    
    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
Пример #13
0
class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head

        h, curr = head, head
        while curr.next:
            prev, curr = curr, curr.next
            if curr.val != prev.val:
                h.next = curr
                h = h.next
        h.next = None
        return head


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    nums1 = [1, 1, 2, 3, 3]
    arguments = [LinkedList(nums1).head]
    answers = [[1, 2, 3]]
    test(Solution().deleteDuplicates, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
        dummy = ListNode(None)
        dummy.next = head
        prev = dummy
        while True:
            h = prev
            for i in xrange(k):
                h = h.next
                if not h:
                    return dummy.next

            t = p = prev.next
            node = p.next
            for i in xrange(k - 1):
                next_node = node.next
                node.next, p, node = p, node, next_node
            prev.next, t.next = p, next_node
            prev = t


if __name__ == "__main__":
    from leetcodelib import test
    arguments = [(LinkedList(range(10)).head, i + 1) for i in xrange(10)]
    answers = [
        range(10), [1, 0, 3, 2, 5, 4, 7, 6, 9, 8],
        [2, 1, 0, 5, 4, 3, 8, 7, 6, 9], [3, 2, 1, 0, 7, 6, 5, 4, 8, 9],
        [4, 3, 2, 1, 0, 9, 8, 7, 6, 5], [5, 4, 3, 2, 1, 0, 6, 7, 8, 9],
        [6, 5, 4, 3, 2, 1, 0, 7, 8, 9], [7, 6, 5, 4, 3, 2, 1, 0, 8, 9],
        [8, 7, 6, 5, 4, 3, 2, 1, 0, 9], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    ]
    test(Solution2().reverseKGroup, arguments, answers, inds=[])
Пример #15
0
        prev, node = None, head
        while node:
            next_node = node.next
            node.next = prev
            prev, node = node, next_node
        return prev
    
class Solution2(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None
        if not head.next:
            return head
        new_head = self.reverseList(head.next)
        head.next.next, head.next = head, None
        return new_head

if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    arguments = [LinkedList([1, 2]).head]
    answers = [[2, 1]]
    test(Solution2().reverseList, arguments, answers)
    
    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
        root = TreeNode(None)
        level = [root]
        curr = head
        while True:
            tmp = []
            for node in level:
                if not curr.next:
                    return root
                node.left = TreeNode(None)
                tmp.append(node.left)
                curr = curr.next
                if not curr.next:
                    return root
                node.right = TreeNode(None)
                tmp.append(node.right)
                curr = curr.next
            level = tmp


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    nums_list = [range(100)]
    linkedlists = [LinkedList(x) for x in nums_list]
    arguments = [x.head for x in linkedlists]
    answers = nums_list
    test(Solution().sortedListToBST, arguments, answers, mode='inorder')

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)
Пример #17
0
        fast = head
        for _ in xrange(n):
            fast = fast.next

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

        discarded = slow.next
        slow.next = discarded.next
        discarded.next = None

        return dummy.next


if __name__ == "__main__":
    from leetcodelib import LinkedList
    nums = range(1, 10)
    #n = len(nums)
    #n = 1
    n = 4
    answer = nums[:len(nums) - n] + nums[len(nums) - n + 1:]
    testlist = LinkedList(nums)
    newhead = Solution().removeNthFromEnd(testlist.head, n)
    result = LinkedList().values(newhead)
    print answer
    print result
    print answer == result
Пример #18
0
        """
        p1, p2 = l1, l2
        head = ListNode(0)
        prev, node = None, head
        while p1 or p2 or node.val >= 10:
            n1 = p1.val if p1 else 0
            n2 = p2.val if p2 else 0
            q, r = divmod(n1 + n2 + node.val, 10)
            node.val = r
            node.next = ListNode(q)
            p1 = p1.next if p1 else None
            p2 = p2.next if p2 else None
            prev, node = node, node.next
        if node.val == 0 and prev:
            prev.next = None
        return head


if __name__ == "__main__":
    from leetcodelib import test, update_testfile, run_testfile
    nums1 = [9, 9, 9]
    nums2 = [1]
    arguments = [(LinkedList(nums1).head, LinkedList(nums2).head)]
    answers = [[0, 0, 0, 1]]
    test(Solution2().addTwoNumbers, arguments, answers)

    #testfile = __file__.replace('.py', '.yaml')
    #arg_names = ""
    #update_testfile(testfile, arg_names, arguments, answers)
    #run_testfile(testfile, Solution().)