All problems

Problem 383

Sort a Linked List

Medium · 20 pts · Linked List, Sorting, Divide and Conquer

Problem

Sort a singly linked list in ascending order and print it. On a real linked list you cannot jump to the middle in O(1), so quicksort and heapsort are awkward; merge sort fits naturally: split the list in half with slow and fast pointers, sort both halves recursively, and merge them. This runs in O(N log N) time.

Input

The first line contains N, the number of nodes. The second line contains the N node values from head to tail.

Output

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

Constraints

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

Example input

4
4 2 1 3

Example output

1 2 3 4

Explanation

Merge sort splits 4 2 1 3 into 4 2 and 1 3, sorts them into 2 4 and 1 3, and merges those into 1 2 3 4.

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

Previous: Odd Even Linked List Next: Swap Kth Nodes from Both Ends