Suppose that you have a linked list of integers containing nodes that are instan
ID: 3630059 • Letter: S
Question
Suppose that you have a linked list of integers containing nodes that areinstances of the following class:
public class IntNode {
private int val;
private IntNode next;
}
a. Write a method named printOddsRecursive() that takes a reference to the
first node in a linked list of IntNodes and uses recursion to print the odd
values in the list (if any), with each value printed on a separate line. If there
are no odd values, the method should not do any printing.
b. Write a method named printOddsIterative() that uses iteration to
perform the same task.
You do not need to code up this method as part of a class – a written version of
the method itself is all that is required. You may assume that the method you
write is a static method of the IntNode class.
Explanation / Answer
Recursive:
public static void printOddsRecursive(IntNode root)
{
// break case: root is null
if(root == null)
return;
// check if root value is odd, if so print it
if(root.val % 2 == 1)
System.out.println(root.val);
// move to next node
printOddsRecursive(root.next);
}
Iterative:
public static void printOddsRecursive(IntNode root)
{
// break case: root is null
while(root != null)
{
// check if root value is odd, if so print it
if(root.val % 2 == 1)
System.out.println(root.val);
// move to next node
root = root.next;
}
}
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.