KatInterview

143. Reorder List

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to reorder a singly linked list L0 → L1 → … → Ln-1 → Ln into the form L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …. This must be done in-place, meaning we should modify the pointers of the existing nodes without creating a new list or changing node values.

Solution

Reorder List in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        # Handle edge cases: 0, 1, or 2 nodes
        if not head or not head.next or not head.next.next:
            return

        # Step 1: Find the middle of the list
        # slow will point to the end of the first half
        slow, fast = head, head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        
        # head2 is the start of the second half
        head2 = slow.next
        # Split the list into two halves
        slow.next = None

        # Step 2: Reverse the second half
        prev = None
        curr = head2
        while curr:
            next_temp = curr.next
            curr.next = prev
            prev = curr
            curr = next_temp
        head2_reversed = prev

        # Step 3: Merge the two halves
        p1, p2 = head, head2_reversed
        while p2:
            p1_next = p1.next
            p2_next = p2.next
            
            # Interleave
            p1.next = p2
            p2.next = p1_next
            
            # Move to the next pair of nodes
            p1 = p1_next
            p2 = p2_next

Reorder List in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public void reorderList(ListNode head) {
        // Handle edge cases: 0, 1, or 2 nodes
        if (head == null || head.next == null || head.next.next == null) {
            return;
        }

        // Step 1: Find the middle of the list
        // slow will point to the end of the first half
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        // head2 is the start of the second half
        ListNode head2 = slow.next;
        // Split the list into two halves
        slow.next = null;

        // Step 2: Reverse the second half
        ListNode prev = null;
        ListNode curr = head2;
        while (curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        ListNode head2Reversed = prev;

        // Step 3: Merge the two halves
        ListNode p1 = head;
        ListNode p2 = head2Reversed;
        while (p2 != null) {
            ListNode p1Next = p1.next;
            ListNode p2Next = p2.next;

            // Interleave
            p1.next = p2;
            p2.next = p1Next;

            // Move to the next pair of nodes
            p1 = p1Next;
            p2 = p2Next;
        }
    }
}

Reorder List in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        // Handle edge cases: 0, 1, or 2 nodes
        if (!head || !head->next || !head->next->next) {
            return;
        }

        // Step 1: Find the middle of the list
        // slow will point to the end of the first half
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast->next && fast->next->next) {
            slow = slow->next;
            fast = fast->next->next;
        }

        // head2 is the start of the second half
        ListNode* head2 = slow->next;
        // Split the list into two halves
        slow->next = nullptr;

        // Step 2: Reverse the second half
        ListNode* prev = nullptr;
        ListNode* curr = head2;
        while (curr) {
            ListNode* nextTemp = curr->next;
            curr->next = prev;
            prev = curr;
            curr = nextTemp;
        }
        ListNode* head2Reversed = prev;

        // Step 3: Merge the two halves
        ListNode* p1 = head;
        ListNode* p2 = head2Reversed;
        while (p2) {
            ListNode* p1Next = p1->next;
            ListNode* p2Next = p2->next;

            // Interleave
            p1->next = p2;
            p2->next = p1Next;

            // Move to the next pair of nodes
            p1 = p1Next;
            p2 = p2Next;
        }
    }
};

Reorder List in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

/**
 Do not return anything, modify head in-place instead.
 */
function reorderList(head: ListNode | null): void {
    // Handle edge cases: 0, 1, or 2 nodes
    if (!head || !head.next || !head.next.next) {
        return;
    }

    // Step 1: Find the middle of the list
    // slow will point to the end of the first half
    let slow: ListNode = head;
    let fast: ListNode | null = head;
    while (fast.next && fast.next.next) {
        slow = slow.next!;
        fast = fast.next.next;
    }

    // head2 is the start of the second half
    let head2: ListNode | null = slow.next;
    // Split the list into two halves
    slow.next = null;

    // Step 2: Reverse the second half
    let prev: ListNode | null = null;
    let curr: ListNode | null = head2;
    while (curr) {
        const nextTemp = curr.next;
        curr.next = prev;
        prev = curr;
        curr = nextTemp;
    }
    let head2Reversed: ListNode | null = prev;

    // Step 3: Merge the two halves
    let p1: ListNode | null = head;
    let p2: ListNode | null = head2Reversed;
    while (p2) {
        const p1Next = p1!.next;
        const p2Next = p2.next;
        
        // Interleave
        p1!.next = p2;
        p2.next = p1Next;
        
        // Move to the next pair of nodes
        p1 = p1Next;
        p2 = p2Next;
    }
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.