Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the length counter to zero.
DSA C++
int getLength(Node* head) {
int length = [1];
Node* current = head;
while (current != nullptr) {
length++;
current = current->next;
}
return length;
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting length at 1 instead of 0
Initializing length with head pointer
Using nullptr as initial length
✗ Incorrect
The length counter should start at 0 before counting nodes.
2fill in blank
mediumComplete the code to move to the next node in the linked list.
DSA C++
int getLength(Node* head) {
int length = 0;
Node* current = head;
while (current != nullptr) {
length++;
current = [1];
}
return length;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using head->next instead of current->next
Assigning current to itself causing infinite loop
Setting current to nullptr prematurely
✗ Incorrect
To move forward, update current to current->next.
3fill in blank
hardFix the error in the while loop condition to correctly check the end of the list.
DSA C++
int getLength(Node* head) {
int length = 0;
Node* current = head;
while ([1]) {
length++;
current = current->next;
}
return length;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using current == nullptr which ends loop immediately
Checking head instead of current in loop
Using incorrect null checks causing runtime errors
✗ Incorrect
The loop should continue while current is not nullptr.
4fill in blank
hardComplete the for loop to traverse the linked list and count its length.
DSA C++
int getLength(Node* head) {
int length = 0;
for (Node* current = head; [1]; [2]) {
length++;
}
return length;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using head != nullptr in the condition instead of current
Incorrect update like current = head->next
Confusing while loop syntax with for loop
✗ Incorrect
Use 'current != nullptr' as the loop condition and 'current = current->next' as the update expression.
5fill in blank
hardComplete the recursive version of getLength by filling the base case condition, base case return value, and recursive call.
DSA C++
int getLength(Node* head) {
if ([1]) {
return [2];
}
return 1 + getLength([3]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using head != nullptr as base case condition
Returning 1 instead of 0 in base case
Recursive call on head instead of head->next causing infinite recursion
✗ Incorrect
Base case: if (head == nullptr) return 0; Recursive case: return 1 + getLength(head->next);
