Algo-Sim › Linked Lists

Reorder List

Medium · Linked Lists · step through it in Java, Python and C++ on your own input

Reorder L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place: find the middle, reverse the back half, weave.

Problem

Rearrange the list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → L2 → …, alternating from the front and the back. Change the links between nodes, not the values stored in them.

Constraints

Edge cases to test

Follow-up questions

Why cut the list at the middle?
Otherwise the front half still points into the back half and the weave creates a cycle.
What is the simpler O(n)-space version?
Put the nodes in an array and relink from both ends.

Solution

Java

public void reorderList(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    ListNode prev = null, curr = slow.next;
    slow.next = null;
    while (curr != null) {
        ListNode next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    ListNode first = head, second = prev;
    while (second != null) {
        ListNode n1 = first.next, n2 = second.next;
        first.next = second;
        second.next = n1;
        first = n1;
        second = n2;
    }
}

Python

def reorder_list(head):
    slow = fast = head
    while fast.next and fast.next.next:
        slow = slow.next
        fast = fast.next.next
    prev, curr = None, slow.next
    slow.next = None
    while curr:
        nxt = curr.next
        curr.next = prev
        prev = curr
        curr = nxt
    first, second = head, prev
    while second:
        n1, n2 = first.next, second.next
        first.next = second
        second.next = n1
        first, second = n1, n2

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    void reorderList(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast->next != nullptr && fast->next->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode *prev = nullptr, *curr = slow->next;
        slow->next = nullptr;
        while (curr != nullptr) {
            ListNode *next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }
        ListNode *first = head, *second = prev;
        while (second != nullptr) {
            ListNode *n1 = first->next;
            ListNode *n2 = second->next;
            first->next = second;
            second->next = n1;
            first = n1;
            second = n2;
        }
    }
};

More Linked Lists problems