All problems

Problem 114

Merge Two Sorted Lists

Easy · 10 pts · Linked List, Recursion

Problem

You are given two linked lists, each sorted in non-decreasing order. Merge them into a single sorted list by linking their existing nodes together, and print the result. Either list may be empty. Compare the heads of the two lists, attach the smaller node to the end of the result, and advance in that list. When one list runs out, attach the rest of the other one. A dummy head node keeps the code simple.

Input

Four lines: N, the N values of list 1 (sorted), M, the M values of list 2 (sorted). Either list may be empty.

Output

Print the node values of the resulting list from head to tail, space-separated, or EMPTY if it has no nodes.

Constraints

0 <= N, M <= 50000; -100000 <= value <= 100000

Example input

3
1 2 4
3
1 3 4

Example output

1 1 2 3 4 4

Explanation

Merging 1 → 2 → 4 with 1 → 3 → 4: take 1, then the other 1, then 2, 3, 4 and the last 4. The result is 1 1 2 3 4 4.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Remove Nth Node From End Next: Remove Linked List Elements