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
- 1 ≤ number of nodes ≤ 5 · 10⁴
- 1 ≤ Node.val ≤ 1000
- Rewire nodes in place; values must not be modified
Edge cases to test
- One or two nodes: unchanged
- Odd and even lengths
- Three nodes
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
- Reverse Linked List (Easy)
- Reverse Linked List (Recursive) (Easy)
- Merge Two Sorted Lists (Easy)
- Middle of the Linked List (Easy)
- Palindrome Linked List (Easy)
- Linked List Cycle (Easy)
- Linked List Cycle II (Medium)
- Intersection of Two Linked Lists (Easy)
- Find the Duplicate Number (Medium)
- Remove Nth Node From End of List (Medium)
- Sort List (Medium)
- Add Two Numbers (Medium)
- Copy List with Random Pointer (Medium)
- Reverse Nodes in k-Group (Hard)