361. Odd Even Linked List

MediumLinked ListLinked ListTwo Pointers

Given a singly linked list, group all nodes at odd positions together followed by the nodes at even positions, preserving the relative order within each group. Positions are 1-indexed (the first node is odd). The list is given as an array; return the rearranged array.

Input: An array of node values.

Output: Array — odd-position nodes then even-position nodes.

Examples

Example 1
Input: [1,2,3,4,5]
Output: [1,3,5,2,4]
Explanation: Odd positions 1,3,5 then even 2,4.
Example 2
Input: [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]
Explanation: Grouped by position parity.
Example 3
Input: [1]
Output: [1]
Explanation: Single node.

Constraints

Asked by

AmazonBloombergMicrosoftMetaGoogleApple
Solve this problem in the editor →