Odd-Even Linked List
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
0 ≤ number of nodes in head ≤ 200 - ◆
-1000 ≤ node value ≤ 1000 - ◆
Positions are counted from 1 — the first node is odd-positioned
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Collect into Two Lists, Then Write Back
GoodWalk the list once, sorting every value into one of two arrays based on whether its position is odd or even. Concatenate the odd-positioned values before the even-positioned ones, then walk the list a second time, overwriting each node's value in that new order. Correct, but the two arrays cost O(n) extra space where the optimal solution needs none.
O(n)O(n)1// Node definition used in this problem:
2// class Node {
3// int val;
4// Node next;
5// }
6
7class Solution {
8 public Node oddEvenList(Node head) {
9 List<Integer> odds = new ArrayList<>();
10 List<Integer> evens = new ArrayList<>();
11 Node curr = head;
12 int idx = 0;
13 while (curr != null) {
14 if (idx % 2 == 0) {
15 odds.add(curr.val);
16 } else {
17 evens.add(curr.val);
18 }
19 curr = curr.next;
20 idx++;
21 }
22 List<Integer> combined = new ArrayList<>(odds);
23 combined.addAll(evens);
24 curr = head;
25 for (int v : combined) {
26 curr.val = v;
27 curr = curr.next;
28 }
29 return head;
30 }
31}Optimal — Relink in Place with Two Pointers
OptimalCarry two pointers, odd and even, starting at the first and second nodes, and remember the even list's head separately since it needs to be reattached at the very end. At each step, odd skips over the node right after it (landing on the next odd-positioned node), and even does the same (landing on the next even-positioned node) — splicing every node out of its original spot and into one of the two growing chains as the pointers advance together. Once even runs out of nodes, the odd chain's tail is pointed at the remembered even-chain head, joining the two chains with no extra memory beyond the pointers themselves.
O(n)O(1)1// Node definition used in this problem:
2// class Node {
3// int val;
4// Node next;
5// }
6
7class Solution {
8 public Node oddEvenList(Node head) {
9 if (head == null || head.next == null) return head;
10 Node odd = head;
11 Node even = head.next;
12 Node evenHead = even;
13 while (even != null && even.next != null) {
14 odd.next = even.next;
15 odd = odd.next;
16 even.next = odd.next;
17 even = even.next;
18 }
19 odd.next = evenHead;
20 return head;
21 }
22}