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;
while (fast != null && fast.next != null) {
slow = slow.[1];
fast = fast.next.next;
}
return slow;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using fast.next instead of slow.next for the slow pointer.
Using prev which is not defined in singly linked list.
✗ Incorrect
To find the middle node, the slow pointer moves one step at a time using slow.next.
2fill in blank
mediumComplete the code to merge two sorted linked lists.
DSA C#
ListNode Merge(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
tail.next = l1;
l1 = l1.[1];
} else {
tail.next = l2;
l2 = l2.next;
}
tail = tail.next;
}
tail.next = (l1 != null) ? l1 : l2;
return dummy.next;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using l1.val instead of l1.next to move the pointer.
Using prev which is not defined in singly linked list.
✗ Incorrect
To move forward in the list, use l1.next to advance the pointer.
3fill in blank
hardFix the error in the recursive merge sort call to sort the right half.
DSA C#
ListNode MergeSort(ListNode head) {
if (head == null || head.next == null) return head;
ListNode mid = FindMiddle(head);
ListNode rightHead = mid.next;
mid.next = null;
ListNode left = MergeSort(head);
ListNode right = MergeSort([1]);
return Merge(left, right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using mid instead of rightHead for the right half.
Using head again which is the start of the left half.
✗ Incorrect
The right half starts at rightHead, so we recursively sort from rightHead.
4fill in blank
hardFill both blanks to correctly split the linked list into two halves.
DSA C#
ListNode FindMiddle(ListNode head) {
ListNode slow = head;
ListNode fast = head.[1];
while (fast != null && fast.[2] != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting fast at head instead of head.next.
Using 'prev' which is not defined in singly linked list.
✗ Incorrect
Fast pointer starts at head.next and moves two steps using fast.next.next.
5fill in blank
hardFill both blanks to complete the merge sort implementation for linked list.
DSA C#
public ListNode SortList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode mid = FindMiddle(head);
ListNode rightHead = mid.[1];
mid.[2] = null;
ListNode left = SortList(head);
ListNode right = SortList(rightHead);
return Merge(left, right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' which is not defined in singly linked list.
Not breaking the list by setting mid.next to null.
✗ Incorrect
To split the list, use mid.next to get rightHead and set mid.next to null to break the list.
