Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Can someone please help. I have created a recursive method to print out the foll

ID: 3662657 • Letter: C

Question

Can someone please help. I have created a recursive method to print out the following: 1 2 5 5 8 9 5. I now need to print it out in reverse: 5 9 8 5 5 2 1.

Can someone please help me with the code so I can see what I am doing wrong. Here is the code:

public class List {

class Node {
public int info;
public Node next = null;

public Node(int el, Node ref) {
info = el;
next = ref;
}
}

private Node head = null;
private static int lastNumber = 99;
private static int count = 0;

public void addToHead(int el) {
head = new Node(el, head);
}
// Do not modify any code above this line.
// Write printRecursion method here. This must be a recursive method.

public static void printRecursion(Node temp)
{
if (temp == null)
{
System.out.println();
return;
}
else
{

System.out.print(temp.info + " ");
temp = temp.next;
printRecursion(temp);

}
}



private static void displayName(){
System.out.println("This program is written by David Kirk. ");
}

// DO NOT MODIFY MAIN METHOD
public static void main(String[] args) {
displayName();
List list = new List();
list.addToHead(5); list.addToHead(9); list.addToHead(8);
list.addToHead(5); list.addToHead(5);
list.addToHead(2); list.addToHead(1);
printRecursion(list.head);
System.out.println(" Count of last number: "+count);
System.out.println("Good Bye...");
}

}

Explanation / Answer

below are the code with underline the changes:

class List {

class Node {
public int info;
public Node next = null;

public Node(int el, Node ref) {
info = el;
next = ref;
}
}

private Node head = null;
private static int lastNumber = 99;
private static int count = 0;

public void addToHead(int el) {
head = new Node(el, head);
}
// Do not modify any code above this line.
// Write printRecursion method here. This must be a recursive method.

public static void printRecursion(Node temp)
{
if (temp == null) return;

// print list of head node
printRecursion(temp.next);

// After everything else is printed
System.out.print(temp.info+" ");
}

private static void displayName(){

System.out.println("This program is written by David Kirk. ");
}

// DO NOT MODIFY MAIN METHOD
public static void main(String[] args) {
displayName();
List list = new List();
list.addToHead(5); list.addToHead(9); list.addToHead(8);
list.addToHead(5); list.addToHead(5);
list.addToHead(2); list.addToHead(1);
printRecursion(list.head);
System.out.println(" Count of last number: "+count);
System.out.println("Good Bye...");
}

}