Skip to content
RED SAGSkills

Fold a Linked List

A singly linked list L0 -> L1 -> ... -> Ln is given as an array values. Reorder it to L0 -> Ln -> L1 -> Ln-1 -> L2 -> ..., alternating between the front and the back, and return the new order as an array.

On a real list the classic approach is: find the middle, reverse the second half, then weave the two halves together.

Example 1

Input: values = [1,2,3,4]
Output: [1,4,2,3]

Example 2

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

Constraints

  • 0 <= values.length <= 5 * 10^4
Hint 1

Take one element from the front, then one from the back.

Hint 2

Stop when the two ends meet; do not add the meeting element twice.

Discussion 0

Join free to post in the discussion.

Good practice for: Backend Developer, Full Stack Developer, Embedded Systems Engineer, Mobile App Developer, Game Developer

Run checks your code on 3 sample tests. Submit runs all 7 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.