Complete the code to find the middle node of the linked list using the fast and slow pointer technique.
function findMiddle(head) {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow.[1];
fast = fast.next.next;
}
return slow;
}The slow pointer moves one step at a time using next. This helps find the middle node.
Complete the code to merge two sorted linked lists into one sorted list.
function mergeLists(l1, l2) {
let dummy = new ListNode(0);
let current = dummy;
while (l1 !== null && l2 !== null) {
if (l1.value < l2.value) {
current.next = l1;
l1 = l1.[1];
} else {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
current.next = l1 !== null ? l1 : l2;
return dummy.next;
}To move forward in the list, we use the next property.
Fix the error in the base case check of the merge sort function for linked list.
function mergeSort(head) {
if (head === null || head.[1] === null) {
return head;
}
// rest of merge sort logic
}The base case checks if the list is empty or has only one node by checking head.next.
Fill both blanks to split the linked list into two halves and recursively sort them.
function mergeSort(head) {
if (head === null || head.next === null) return head;
let middle = findMiddle(head);
let nextToMiddle = middle.[1];
middle.[2] = null;
let left = mergeSort(head);
let right = mergeSort(nextToMiddle);
return mergeLists(left, right);
}We use next to get the node after middle and to break the list by setting middle.next = null.
Fill all three blanks to complete the merge sort function for a linked list.
function mergeSort(head) {
if (head === null || head.next === null) return head;
let middle = [1](head);
let nextToMiddle = middle.[2];
middle.[3] = null;
let left = mergeSort(head);
let right = mergeSort(nextToMiddle);
return mergeLists(left, right);
}We call findMiddle to get the middle node, use next to get the node after middle, and set middle.next = null to split the list.
