Reorder Linked List
Imagine you're building a feature for a music playlist application where users can "shuffle" a playlist in a specific, aesthetically pleasing pattern. Instead of a random shuffle, the design calls for an "interleaved" reordering: the first song, then the last, then the second, then the second-to-last, and so on. This ensures a blend of old and new tracks throughout the listening experience. Your task is to implement this reordering for a given playlist represented as a singly linked list.
Given the head of a singly linked list L: L0 → L1 → … → Ln-1 → Ln, reorder it to L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → ….
You must do this in-place without modifying the nodes' values.
head: A ListNode representing the head of the singly linked list.void). The modified list should be accessible via the original head reference.head is null, the function should do nothing.Examples
Example 1
Input:
head = [1,2,3,4]
Output:
[1,4,2,3]
Note:
The original list is 1 -> 2 -> 3 -> 4. After reordering: 1 -> 4 -> 2 -> 3.
Example 2
Input:
head = [1,2,3,4,5]
Output:
[1,5,2,4,3]
Note:
The original list is 1 -> 2 -> 3 -> 4 -> 5. After reordering: 1 -> 5 -> 2 -> 4 -> 3.
Example 3
Input:
head = [1,2]
Output:
[1,2]
Note:
A list with 2 nodes is already in the desired order, or too short for effective reordering. The list remains 1 -> 2.
Constraints
n in the list is between 0 and 5 * 10^4.Loading editor...