700138. Reorder List

Hard

Here is a detailed Markdown blog post for the "Reorder List" problem:

Reorder List

Summary

Given a singly linked list, reorder its nodes such that all even indices are placed to the right of odd indices. For example, if the input list is 1 -> 2 -> 3 -> 4 -> 5, the output should be 1 -> 3 -> 5 -> 2 -> 4.

This problem involves manipulating a linked list and requires an understanding of basic data structures and algorithms.

Detailed Explanation

The key to solving this problem is to maintain two pointers: one for even indices and another for odd indices. We iterate through the linked list, moving the pointers accordingly. Whenever we encounter an even-indexed node, we move the even pointer ahead by one step. Similarly, whenever we encounter an odd-indexed node, we move the odd pointer ahead by one step.

Here's a step-by-step breakdown of the solution:

  1. Initialize two pointers: even and odd. Set even to the head of the linked list and set odd to the next node.
  2. Iterate through the linked list until odd reaches the end.
  3. When we encounter an even-indexed node (i.e., even is pointing to it), move even ahead by one step.
  4. When we encounter an odd-indexed node (i.e., odd is pointing to it), swap the nodes at even and odd. Move both pointers ahead by one step.
  5. Repeat steps 2-4 until odd reaches the end.

Time complexity: O(n), where n is the number of nodes in the linked list. We only iterate through the linked list once, so the time complexity is linear. Space complexity: O(1), since we only use a constant amount of space to store the two pointers and no extra data structures are required.

Optimized Solutions

Java

View on GeeksforGeeks
public ListNode reorderList(ListNode head) {
    if (head == null || head.next == null) return head;

    // Find the middle of the linked list
    ListNode slow = head;
    ListNode fast = head;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }

    // Reverse the second half of the linked list
    ListNode mid = slow.next;
    slow.next = null;

    // Merge the two halves in alternating order
    ListNode dummy = new ListNode(0);
    ListNode curr = dummy;
    while (head != null || mid != null) {
        if (head == null) head = mid;
        else if (mid == null) mid = head;
        curr.next = head;
        head = head.next;
        curr = curr.next;

        curr.next = mid;
        mid = mid.next;
        curr = curr.next;
    }

    return dummy.next;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.