Problem
Problem page: https://leetcode.com/problems/reorder-list/
Topics: Linked List
Difficulty: Medium
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…You must do this in-place without altering the nodes' values.
For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.
Analysis
I start by counting the nodes and return without changing anything if count is 2 or less; otherwise I split the list in the middle, leaving the first ceil(count/2) nodes in the first half. In the code, half_count = (count - 1) / 2. I move cur2 forward half_count steps from head, which puts it on the last node of the first half. Then cur2.next = None separates the two halves.
I reverse the second half in place, leaving the first half in its original order, so I don't need to copy the list.
As I walk the first half, I insert the next node from the reversed second half after the current node. That's count / 2 insertions (integer division). For example, with {1,2,3,4}, I reverse the second half to get 4→3 and interleave it with the first half 1→2 to get 1→4→2→3. I only change next pointers along the way, and the whole operation takes O(n) time and O(1) extra space.
Code
1 | # Reverse the nodes from head up to (but not including) end, and link the |
Article link: https://xnerv.wang/en/leetcode-reorder-list/
