Пример #1
0
def merge(l1, l2):

    dummy = ListNode(-1)
    p = dummy
    while l1 and l2:
        if l1.val < l2.val:
            p.next = l1
            l1 = l1.next
        else:
            p.next = l2
            l2 = l2.next
        p = p.next

    if l1:
        p.next = l1
        l1 = l1.next
        p = p.next

    if l2:
        p.next = l2
        l2 = l2.next
        p = p.next

    return dummy.next

if __name__ == '__main__':
    l0 = ListNode.build_from_array([1, 2, 3, 4, -5, -6])
    ListNode.traverse(sortList(l0))

Пример #2
0
    dummy = ListNode(-999999999999)
    dummy.next = head

    # 'd -> 1, 3, | 2,1,4,5'
    p1 = head
    p2 = head.next
    while p2:
        if p2.val < p1.val:
            # do the insert
            p = p2
            p2 = p2.next
            p1.next = p2
            pp = dummy
            while pp.next.val < p.val:
                pp = pp.next
            p.next = pp.next
            pp.next = p

        else:
            p1 = p2
            p2 = p2.next

    return dummy.next


if __name__ == '__main__':
    l0 = ListNode.build_from_array([1,2,-3])
    print(ListNode.traverse(insertionSortList(l0)))

Пример #3
0
    s = dummy
    p = head

    counter = 1
    while counter < m:
        s = s.next
        p = p.next
        counter += 1

    while counter < n:
        tmp = s.next
        s.next = p.next
        p.next = p.next.next
        s.next.next = tmp
        counter += 1

    return dummy.next


if __name__ == '__main__':

    h0 = ListNode.build_from_array([1, 2, 3, 4, 5])
    ListNode.traverse(reverse_between(h0, 2, 4))

    h0 = ListNode.build_from_array([1, 2, 3, 4, 5])
    ListNode.traverse(reverse_between(h0, 1, 5))

    h0 = ListNode.build_from_array([1])
    ListNode.traverse(reverse_between(h0, 1, 1))