700138. Reorder List
Here is a detailed Markdown blog post for the "Reorder List" problem:
Reorder List
Summary
Given a singly linked list, reorder its nodes such that all even indices are placed to the right of odd indices. For example, if the input list is 1 -> 2 -> 3 -> 4 -> 5, the output should be 1 -> 3 -> 5 -> 2 -> 4.
This problem involves manipulating a linked list and requires an understanding of basic data structures and algorithms.
Detailed Explanation
The key to solving this problem is to maintain two pointers: one for even indices and another for odd indices. We iterate through the linked list, moving the pointers accordingly. Whenever we encounter an even-indexed node, we move the even pointer ahead by one step. Similarly, whenever we encounter an odd-indexed node, we move the odd pointer ahead by one step.
Here's a step-by-step breakdown of the solution:
- Initialize two pointers:
evenandodd. Setevento the head of the linked list and setoddto the next node. - Iterate through the linked list until
oddreaches the end. - When we encounter an even-indexed node (i.e.,
evenis pointing to it), moveevenahead by one step. - When we encounter an odd-indexed node (i.e.,
oddis pointing to it), swap the nodes atevenandodd. Move both pointers ahead by one step. - Repeat steps 2-4 until
oddreaches the end.
Time complexity: O(n), where n is the number of nodes in the linked list. We only iterate through the linked list once, so the time complexity is linear. Space complexity: O(1), since we only use a constant amount of space to store the two pointers and no extra data structures are required.
Optimized Solutions
Java
public ListNode reorderList(ListNode head) {
if (head == null || head.next == null) return head;
// Find the middle of the linked list
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// Reverse the second half of the linked list
ListNode mid = slow.next;
slow.next = null;
// Merge the two halves in alternating order
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
while (head != null || mid != null) {
if (head == null) head = mid;
else if (mid == null) mid = head;
curr.next = head;
head = head.next;
curr = curr.next;
curr.next = mid;
mid = mid.next;
curr = curr.next;
}
return dummy.next;
}