Problem description

Given the head of a singly linked list, reorder it so that every node sitting at an odd position comes before every node sitting at an even position. Positions are counted starting from 1, based on where the nodes currently sit, not on their values.

Within the odd group and within the even group the original relative order must be preserved. The rearrangement has to run in O(1) extra space and O(n) time.

Example 1

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

Output: [1,3,5,2,4]

Odd-position nodes 1, 3, 5 are chained first, then the even-position nodes 2 and 4 follow.

Example 2

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

Output: [2,3,6,7,1,5,4]

Positions 1,3,5,7 hold 2,3,6,7 and positions 2,4,6 hold 1,5,4; the odd group leads and the even group trails.

Constraints

  • The number of nodes is in the range [0, 10^4].
  • -10^6 <= Node.val <= 10^6

After the pattern

Now solve one you haven't seen.

Regroup the Bucket Line is our own problem on the technique behind Odd Even Linked List: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free