1590. Odds Forward Evens Back

Medium3.5 points estimatedLinked ListTwo Pointers

A warehouse conveyor is modelled as a singly linked list of crates, and the night shift wants a quick reshuffle: crates standing at odd 1-based positions are sent forward in their original order, and the crates at even positions are loaded behind them in reverse order. Write oddsForwardEvensBack(head), which relinks the nodes of the list that starts at head in place and returns nothing; the judge reads the list back from head, which always stays the first node. For example 1, 2, 3, 4, 5 becomes 1, 3, 5, 4, 2. Do not copy values into a new list. The list has 1 to 100000 nodes. Aim for O(n) time and O(1) extra space.

Example 1

Input:
head = [1,2,3,4,5]
Output:
[1,3,5,4,2]
Explanation:

Odd positions hold 1, 3, 5 and even positions hold 2, 4, which are appended as 4, 2.

Example 2

Input:
head = [10,20,30,40]
Output:
[10,30,40,20]
Explanation:

Odd positions give 10, 30; even positions 20, 40 are appended reversed as 40, 20.

Constraints

1 ≤ length ≤ 105

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Graded
Your answer is read from head after your method returns.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…