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

Java I need to write a Recursive function to find the size of a linked list with

ID: 3594347 • Letter: J

Question

Java

I need to write a Recursive function to find the size of a linked list with a helper function. the static class is how we build the list and below is for the Recursive function.

static class Node {

       public Node (double item, Node next) { this.item = item; this.next = next; }

       public double item;

       public Node next;

   }

   Node first;

// a function to compute the size of the list using recursion

   // empty list has size 0

   // You will want to create a helper function to do the recursion

   public int sizeRecursive () {

       return 0;

  

   }

Explanation / Answer

Copy the code in a java file named as LinkedList.java

Compile command : javac LinkedList.java

Run Command : java LinkedList

Code Snippet :

public class LinkedList{
public Node head;
public LinkedList(){}
public LinkedList(Node head){
this.head=head;
}
static class Node {
public Node (double item, Node next) {
this.item = item; this.next = next;
}
public double item;
public Node next;
}

public int sizeRecursive () {
if (head==null) return 0;
else {
head = head.next;
return 1 + sizeRecursive();
}

}
public static void main(String [] args){
LinkedList lList = new LinkedList();
lList.head = new Node(10d, null);
  
//Node2
Node node2 = new Node(20d, null);
lList.head.next=node2;
//Node3
Node node3 = new Node(30d, null);
node2.next=node3;
//Node4
Node node4 = new Node(40d, null);
node3.next=node4;
//Node5
Node node5 = new Node(50d, null);
node4.next=node5;

Node temp = lList.head;
while(temp!=null){
System.out.println(temp.item);
temp=temp.next;
}
int size = lList.sizeRecursive();
System.out.println("Size: " + size);
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote