Reorder List
mediumLinked List+20 XPTime limit 2s
Reorder the list L0 → L1 → … → Ln−1 into L0 → Ln−1 → L1 → Ln−2 → L2 → … (first, last, second, second-last, …).
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: one list (n ≥ 1).
Output: the reordered list.
Constraints: 1 ≤ n ≤ 10⁵.
Challenge: do it on the nodes in O(1) extra memory by combining three classic moves: find the middle, reverse the second half, then merge the two halves alternately.
Sample input 1
4 1 2 3 4
Sample output 1
1 4 2 3
Sample input 2
5 1 2 3 4 5
Sample output 2
1 5 2 4 3
📖 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).