def main(): head1 = create_linked_list([4, 8, 15, 19]) head2 = create_linked_list([7, 9, 10, 16]) print("head1: " + print_linked_list(head1)) print("head2: " + print_linked_list(head2)) head1 = merge_sorted(head1, head2) print("merged (head1): " + print_linked_list(head1))
def test(self): s = Solution() l1 = create_linked_list([9, 9]) l2 = create_linked_list([1]) result = print_linked_list(s.addTwoNumbers(l1, l2)) self.assertListEqual([0, 0, 1], result)
if lst1.data < lst2.data: tail.next = lst1 # the FIRST tail.next node is where the actual merge begins lst1 = lst1.next else: tail.next = lst2 lst2 = lst2.next tail = tail.next # append the remaining nodes of list 1 or list 2 tail.next = lst1 or lst2 # when one list becomes None, the 'or' returns the remaining nodes of the other return dummy_head.next # dummy_head.next is the node appended with the FIRST tail.next statement if __name__ == '__main__': lst1 = ListNode(2) lst2 = ListNode(3) insert_after(lst1, ListNode(5)) insert_after(lst1.next, ListNode(7)) insert_after(lst2, ListNode(11)) print("List 1: ") print_linked_list(lst1) print("\nList 2: ") print_linked_list(lst2) res = merge_two_sorted_lists(lst1, lst2) print("\nLists sorted and merged: ") print_linked_list(res)
def test(self): s = Solution() l1 = create_linked_list([1, 2, 4]) l2 = create_linked_list([1, 3, 4]) self.assertListEqual([1, 1, 2, 3, 4, 4], print_linked_list(s.mergeTwoLists(l1, l2)))
def test(self): l1 = create_linked_list([1, 4, 5]) l2 = create_linked_list([1, 3, 5]) l3 = create_linked_list([2, 6]) s = Solution2().mergeKLists([l1, l2, l3]) self.assertListEqual([1, 1, 2, 3, 4, 5, 5, 6], print_linked_list(s))
move temp = 4 to the head of the sublist 2.next = 4.next = 5 (2 followed by 5), temp.next = head.next = 3 (4 followed by 3), head.next = temp = 4 => 4, 3, 2, 5 Step 4: head = 1, iterator = 2, temp = iterator.next = 5 move temp = 5 to the head of the sublist... => 5, 4, 3, 2 The node that follows iterator is always the one to move to the head of the sublist ''' sublist_iter = sublist_head.next for _ in range(finish - start): temp = sublist_iter.next sublist_iter.next = temp.next temp.next = sublist_head.next sublist_head.next = temp return dummy_head.next # dummy_head.next points to lst if __name__ == '__main__': lst = ListNode(11) insert_after(lst, ListNode(3)) insert_after(lst.next, ListNode(5)) insert_after(lst.next.next, ListNode(7)) insert_after(lst.next.next.next, ListNode(2)) print("Original list: ") print_linked_list(lst) reverse_sublist(lst, 2, 4) print("\nList after reversal: ") print_linked_list(lst)
def test(self): s = BetterSolution() lst = create_linked_list([1, 2, 3, 4]) self.assertListEqual([2, 1, 4, 3], print_linked_list(s.swapPairs(lst)))