Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the length counter to zero.
DSA Javascript
function getLength(head) {
let length = [1];
let current = head;
while (current !== null) {
length++;
current = current.next;
}
return length;
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting length at 1 instead of 0
Initializing length with null or head
✗ Incorrect
The length counter should start at 0 because we haven't counted any nodes yet.
2fill in blank
mediumComplete the code to move to the next node in the linked list.
DSA Javascript
function getLength(head) {
let length = 0;
let current = head;
while (current !== null) {
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
✗ Incorrect
To move to the next node, update current to current.next.
3fill in blank
hardFix the error in the while loop condition to correctly check the end of the linked list.
DSA Javascript
function getLength(head) {
let length = 0;
let current = head;
while (current [1] null) {
length++;
current = current.next;
}
return length;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' which assigns instead of compares
Using '==' or '===' which checks equality, not inequality
✗ Incorrect
The loop should continue while current is not null, so use '!='.
4fill in blank
hardFill both blanks to create a function that returns the length of a linked list using a for loop.
DSA Javascript
function getLength(head) {
let length = 0;
for (let current = head; current [1] null; current = [2]) {
length++;
}
return length;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of !== in loop condition
Updating current to head.next instead of current.next
✗ Incorrect
The for loop continues while current is not null (using !==), and current moves to current.next each iteration.
5fill in blank
hardFill all three blanks to create a recursive function that returns the length of a linked list.
DSA Javascript
function getLength(node) {
if (node [1] null) {
return [2];
} else {
return 1 + getLength([3]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using != or !== in base case instead of ===
Returning node instead of 0 at base case
Recursing on node instead of node.next
✗ Incorrect
If node is null (=== null), return 0. Otherwise, return 1 plus the length of the rest of the list (node.next).
