Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the middle node of the linked list.
DSA C++
ListNode* findMiddle(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head->next;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->[1];
fast = fast->next->next;
}
return slow;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' instead of 'next' causes the pointer to move backward.
Using 'child' or 'random' are invalid for singly linked lists.
✗ Incorrect
The slow pointer moves one step at a time using 'next' to find the middle node.
2fill in blank
mediumComplete the code to fill in the blanks to merge two sorted linked lists.
DSA C++
ListNode* merge(ListNode* l1, ListNode* l2) {
if (!l1) return l2;
if (!l2) return l1;
if (l1->val < l2->val) {
l1->next = merge(l1->next, [1]);
return l1;
} else {
l2->next = merge([2], l2->next);
return l2;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping l1 and l2 in recursive calls causes wrong merges.
Using nullptr instead of the other list causes loss of nodes.
✗ Incorrect
When l1->val < l2->val, recursively merge l1->next with l2 ('C'). Otherwise, merge l1 ('B') with l2->next.
3fill in blank
hardFix the error in the base case of the mergeSort function.
DSA C++
ListNode* mergeSort(ListNode* head) {
if (head == nullptr || head->[1] == nullptr) {
return head;
}
// rest of merge sort code
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking head->prev is invalid for singly linked lists.
Using unrelated pointers like child or random causes errors.
✗ Incorrect
The base case checks if the list has zero or one node by checking if head or head->next is nullptr.
4fill in blank
hardFill both blanks to split the linked list into two halves.
DSA C++
ListNode* mid = findMiddle(head); ListNode* rightHead = mid->[1]; mid->[2] = nullptr;
Attempts:
3 left
💡 Hint
Common Mistakes
Using prev instead of next breaks the logic in singly linked lists.
Setting the wrong pointer to nullptr causes list corruption.
✗ Incorrect
To split the list, we set rightHead to mid->next and then cut the list by setting mid->next to nullptr.
5fill in blank
hardFill all three blanks to complete the merge sort function for linked list.
DSA C++
ListNode* mergeSort(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode* mid = [1](head);
ListNode* rightHead = mid->[2];
mid->next = nullptr;
ListNode* left = mergeSort(head);
ListNode* right = mergeSort(rightHead);
return [3](left, right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using split instead of merge causes compilation errors.
Not setting mid->next to nullptr causes infinite recursion.
✗ Incorrect
We find the middle using findMiddle, get rightHead by mid->next, and merge the sorted halves using merge.
