oneby7

Linked Lists Reversing and rewiring

305. Odd Even Linked List

Medium

You are given head, the first node of a singly linked list. Number the nodes by their position, starting with 1 at the head. Rearrange the list so that all nodes at odd positions (the 1st, 3rd, 5th and so on) come first, followed by all nodes at even positions (the 2nd, 4th and so on). Inside each group, the nodes keep the order they had. Return the head of the rearranged list.

Odd and even describe a node's position, not the value it holds. A node holding 8 at position 3 belongs to the odd group.

The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. The output shows the node you return the same way, as the list from that node on, and shows null as [].

Example 1

head
12583107
output
12810537

Input: head = [12, 5, 8, 3, 10, 7]

Output: [12,8,10,5,3,7]

Explanation: Positions 1, 3 and 5 hold 12, 8 and 10, so those nodes come first, in that order. Positions 2, 4 and 6 hold 5, 3 and 7, and they follow.

Example 2

head
-490-16
output
-4069-1

Input: head = [-4, 9, 0, -1, 6]

Output: [-4,0,6,9,-1]

Explanation: The odd positions hold -4, 0 and 6, and the even positions hold 9 and -1. With an odd number of nodes, the odd group has one node more.

Example 3

611
head
611
output

Input: head = [6, 11]

Output: [6,11]

Explanation: The node holding 6 is at position 1 and the node holding 11 is at position 2, so nothing moves, even though 11 is the odd value.

Check your understanding

Work out the answer for this input before you write any code.

head = [2, 4, 6, 8, 1]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.