A linked list can be traversed recursively as well as iteratively. We want to co
ID: 3828266 • Letter: A
Question
A linked list can be traversed recursively as well as iteratively. We want to count the number of nodes in a linked list using recursion. Which of the following methods implements this concept? Select the one correct response. int getCount(int count, LinkedNode current) {if (current == null) return count; else {count++; return getCount(count, current)}} int getCount(int count, LinkedNode current) {if (current == null) return count; else {current = current.next; count++; return getCount(count, current)}} int getCount(int count, LinkedNode current) {while(current! = null) return count; else {do{count++; while(current ! = null);}} int getCount(int count, LinkedNode current) {if (current == null) return count; else {current = current.next; return count + getCount(count, current)}}Explanation / Answer
II
int getCount(int count,LinkedNode current)
{
if(current == null) // if current is the last node in the list return the same count value
return count;
else
current = current.next; // make next node of current node the current node
count++; //increment count
return getCount(count,current); // send the incremented value of count recursively until current = null. It will keep on incrementing the value of count and return the number of nodes
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.