Complete the code to find the middle node of the linked list using slow and fast pointers.
ListNode* slow = head; ListNode* fast = head; while (fast != nullptr && fast->next != nullptr) { slow = slow->[1]; fast = fast->next->next; }
The slow pointer moves one step at a time using next to find the middle node.
Complete the code to reverse the second half of the linked list starting from the middle node.
ListNode* prev = nullptr; ListNode* curr = slow; while (curr != nullptr) { ListNode* nextTemp = curr->next; curr->next = [1]; prev = curr; curr = nextTemp; }
To reverse the list, each node's next pointer should point to the previous node.
Fix the error in merging the two halves of the list alternately.
ListNode* first = head; ListNode* second = prev; while (second->next != nullptr) { ListNode* tmp1 = first->next; ListNode* tmp2 = second->next; first->next = second; second->next = [1]; first = tmp1; second = tmp2; }
After linking second to first, second's next should point to the next node of first (tmp1) to maintain order.
Fill both blanks to correctly split the list and prepare for reversal.
ListNode* slow = head; ListNode* fast = head; while (fast != nullptr && fast->next != nullptr) { slow = slow->[1]; fast = fast->next->[2]; } slow->next = nullptr;
Both slow and fast pointers move forward using next to find the middle and split the list.
Fill all three blanks to complete the reorder function that reorders the linked list as required.
void reorderList(ListNode* head) {
if (!head || !head->next) return;
ListNode* slow = head;
ListNode* fast = head;
while (fast && fast->next) {
slow = slow->[1];
fast = fast->next->[2];
}
ListNode* second = slow->next;
slow->next = nullptr;
ListNode* prev = nullptr;
while (second) {
ListNode* tmp = second->next;
second->next = prev;
prev = second;
second = tmp;
}
ListNode* first = head;
second = prev;
while (second) {
ListNode* tmp1 = first->next;
ListNode* tmp2 = second->next;
first->next = second;
second->next = [3];
first = tmp1;
second = tmp2;
}
}The slow and fast pointers move forward using next. When merging, second's next points to tmp1 to alternate nodes.
