Problem
Given the head of a singly linked list, reorder the list so that the nodes follow the patternL0 → Ln → L1 → Ln-1 → L2 → Ln-2 → ....
The nodes themselves must be rearranged without changing their values.
Example(s)
Consider the following example(s) to understand the expected input and output.Input
head = [1, 2, 3, 4]
Output
[1, 4, 2, 3]
Solution
This solution combines Fast and Slow Pointers, Linked List Reversal, and Two Pointers to reorder the list inO(n) time and O(1) extra space.
First, we use the Fast and Slow Pointer technique to find the middle of the linked list. The list is then split into two halves.
Next, we reverse the second half of the list. This gives us the nodes from the end of the original list in the required order.
Finally, we merge the first half and the reversed second half by alternating nodes. For example,
1 → 2 → 3 → 4 becomes 1 → 4 → 2 → 3.
The key idea is that the problem can be broken into three standard linked-list operations: find the middle, reverse the second half, and merge the two halves.
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null) {
return;
}
// Find the middle of the list.
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// Reverse the second half.
ListNode second = slow.next;
slow.next = null;
ListNode prev = null;
while (second != null) {
ListNode next = second.next;
second.next = prev;
prev = second;
second = next;
}
// Merge the two halves.
ListNode first = head;
second = prev;
while (second != null) {
ListNode firstNext = first.next;
ListNode secondNext = second.next;
first.next = second;
second.next = firstNext;
first = firstNext;
second = secondNext;
}
}
}
Complexity
Finding the middle, reversing the second half, and merging the two halves each take linear time. Therefore, the overall time complexity isO(n).
The algorithm uses only a constant number of pointers and does not create additional nodes, so the extra space complexity is
O(1).
Comments
No comments yet. Ask a question or share what helped.