Skip to the code
cf.
+25 XP

#233 Fold a Timeline

medium

A recap screen shows a project's milestones as a linked list L0, L1, ..., Ln. To contrast early and late work, it wants them interleaved from both ends: L0, Ln, L1, Ln-1, L2, Ln-2, ....

Write foldTimeline(head) that relinks the nodes into that order and returns the head. Don't change any val; move the nodes. Use O(1) extra space.

Example 1

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

First 1, then the last 4, then 2, then 3.

Example 2

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

1, 5, 2, 4, and the middle 3 ends the list.

Constraints

  • The list has 0 to 5 * 10^4 nodes.
  • 1 <= node.val <= 1000

Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).