MediumLinked List

Odd Even Linked List

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now