def test_1(self):
        l4 = ListNode(5)
        l3 = ListNode(4)
        l3.next = l4
        l2 = ListNode(3)
        l2.next = l3
        l1 = ListNode(2)
        l1.next = l2
        l0 = ListNode(1)
        l0.next = l1

        new_l = remove_nth_from_end(l0, 2)
        str_new_l = stringify_list(new_l)
        self.assertEqual(str_new_l, '1 -> 2 -> 3 -> 5')
Example #2
0
    def test_1(self):
        l1_2 = ListNode(4)
        l1_1 = ListNode(2)
        l1_1.next = l1_2
        l1_0 = ListNode(1)
        l1_0.next = l1_1

        l2_2 = ListNode(4)
        l2_1 = ListNode(3)
        l2_1.next = l2_2
        l2_0 = ListNode(1)
        l2_0.next = l2_1

        expected = '1 -> 1 -> 2 -> 3 -> 4 -> 4'
        merged = merge_two_lists(l1_0, l2_0)
        self.assertEqual(stringify_list(merged), expected)
    def test_1(self):
        # Build list 1
        l1_2 = ListNode(3)
        l1_1 = ListNode(4)
        l1_1.next = l1_2
        l1_0 = ListNode(2)
        l1_0.next = l1_1

        # Build list 2
        l2_2 = ListNode(4)
        l2_1 = ListNode(6)
        l2_1.next = l2_2
        l2_0 = ListNode(5)
        l2_0.next = l2_1

        sum_list_node_0 = add_two_numbers(l1_0, l2_0)
        self.assertEqual(stringify_list(sum_list_node_0), '7 -> 0 -> 8')
    def test_4(self):
        l7_0 = ListNode(9)
        l7_1 = ListNode(9)
        l7_0.next = l7_1
        l8_0 = ListNode(1)

        sum_list_node_0 = add_two_numbers(l7_0, l8_0)
        self.assertEqual(stringify_list(sum_list_node_0), '0 -> 0 -> 1')
    def test_2(self):
        l1 = ListNode(2)
        l0 = ListNode(1)
        l0.next = l1

        new_l = remove_nth_from_end(l0, 2)
        str_new_l = stringify_list(new_l)
        self.assertEqual(str_new_l, '2')
def reverse(head: ListNode) -> ListNode:
    if not head or not head.next:
        return head

    prev = head
    head = head.next
    prev.next = None

    while head:
        nxt = head.nxt
        head.next = prev
        prev = head
        if nxt:
            head = nxt
        else:
            break

    return head
Example #7
0
def merge_k_lists(lists: List[ListNode]) -> ListNode:
    output = None
    output_head = None

    if len(lists) == 0:
        return None
    elif len(lists) == 1:
        return lists[0]

    heap = None

    # Insert all ListNode values into our MinHeap
    for node in lists:
        while node:
            v = node.val
            if heap is None:
                heap = MinHeap(v)
            else:
                heap.insert(v)
            node = node.next

    if heap is None:
        return None

    # Pop values off of the heap 1 by 1 to assemble merged list
    popped = heap.pop()
    while popped is not None:
        if output is None:
            output = ListNode(popped)
            output_head = output
        else:
            output.next = ListNode(popped)
            output = output.next
        popped = heap.pop()

    return output_head