Skills101
← All coding problems

Merge Two Sorted Lists

easyLinked List+10 XPTime limit 2s

Two linked lists are each sorted in non-decreasing order. Merge them into one sorted list by relinking their nodes.

List format. A linked list is given as two lines: its length n, then its n values from head to tail (the second line is empty when n = 0). When you print a list, print its values on one line separated by spaces, or the word empty if it has no nodes.

Input: two lists, one after the other (4 lines).

Output: the merged list.

Constraints: 0 ≤ n₁, n₂ ≤ 5·10⁴, −10⁵ ≤ value ≤ 10⁵.

Think about it: a dummy head node removes all the special cases for "which list starts the result". Keep a tail pointer and always attach the smaller front node.

Sample input 1

3
1 2 4
3
1 3 4

Sample output 1

1 1 2 3 4 4

Sample input 2

0

0

Sample output 2

empty

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.