Question

JAVA - Write a recursive function that takes a linked list as input and returns all...

JAVA - Write a recursive function that takes a linked list as input and returns all of the elements in the linked list.

Input: 1, 2, 3, 4, 5

Output: (1+2+3+4+5)/5 = 3

What I have:

public static int findMean (Node head, Node cur, int n){

int average = 0;

if (head == null){

if(n == 0)

return 0;

}

if (n > 0){

int sum = n + findMean(head, head.next, n -1);

average = (sum)/n;

}

return average;

}

In the main method:

System.out.println("Average is "+ findMean(head, head.next, 5));

//Should be 3 but gives me 1

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Two methods have been provided considering the following facts:

1) If the call given in the question is to be used.

2) If the call given in the question can be changed.

Method code screenshots:

Method code:

     //Define the method findMean().

     public static int findMean (Node head, Node cur, int n)

     {

         

          //If the head is

          //null then return 0.

          if (head == null)

          {

              return 0;

          }

         

          //Otherwise if the head is pointing

          //to the last element in the list

          //then, return the value of the head.

          else if (head.next == null)

          {

              return head.item;

          }

         

          //Otherwise, recursively call

          //the method to calculate the sum.

          else

          {

             

              int sum = head.item + (findMean(head.next, cur, n-1));

             

              if (head.next == cur)

              {

                   return (head.item + sum)/n;

              }

              else

              {

                   return sum;

              }

          }

     }

Below is the code to test the above given method.

Code Screenshots:

Sample Output:

Code To Copy:

//Define the class Node.

class Node

{

     //Declare the required

     //data members.

     int item;

     Node next;

    

     Node(int d)

     {

          item = d;

          next = null;

     }

}

//Define the class Main.

public class Main {

    

     // Define the main() method.

     public static void main(String args[])

     {

          //Define a linked list.

          Node head = new Node(1);

          head.next = new Node(5);

          head.next.next = new Node(3);

          head.next.next.next = new Node(4);

          head.next.next.next.next = new Node(2);

         

          //Call the method and display the average.

          System.out.println("Average is "+ findMean(head, head.next, 5));

     }

    

     //Define the method findMean().

     public static int findMean (Node head, Node cur, int n)

     {

         

          //If the head is

          //null then return 0.

          if (head == null)

          {

              return 0;

          }

         

          //Otherwise if the head is pointing

          //to the last element in the list

          //then, return the value of the head.

          else if (head.next == null)

          {

              return head.item;

          }

         

          //Otherwise, recursively call

          //the method to calculate the sum.

          else

          {

             

              int sum = head.item + (findMean(head.next, cur, n-1));

             

              if (head.next == cur)

              {

                   return (head.item + sum)/n;

              }

              else

              {

                   return sum;

              }

          }

     }

}

Alt version (If the call to the method can be changed):

Method code screenshots:

Method code:

     public static int findMean (Node head, Node cur, int n)

     {

          if (head == null)

          {

              return 0;

          }

          else if (cur.next == null){

              return cur.item;

          }

          else

          {

              int sum = cur.item + (findMean(head, cur.next, n-1));

              if (head == cur)

              {

                   return sum/n;

              }

              else

              {

                   return sum;

              }

          }

     }

Below is the code to test the above given method.

Code Screenshots:

Sample Output:

Code To Copy:

//Define the class Node.

class Node

{

     //Declare the required

     //data members.

     int item;

     Node next;

    

     Node(int d)

     {

          item = d;

          next = null;

     }

}

public class Main {

    

    

     public static void main(String args[])

     {

          Node head = new Node(1);

          head.next = new Node(5);

          head.next.next = new Node(3);

          head.next.next.next = new Node(4);

          head.next.next.next.next = new Node(2);

          System.out.println("Average is "+ findMean(head, head, 5));

     }

    

     public static int findMean (Node head, Node cur, int n)

     {

          if (head == null)

          {

              return 0;

          }

          else if (cur.next == null){

              return cur.item;

          }

          else

          {

              int sum = cur.item + (findMean(head, cur.next, n-1));

              if (head == cur)

              {

                   return sum/n;

              }

              else

              {

                   return sum;

              }

          }

     }

}

Add a comment
Know the answer?
Add Answer to:
JAVA - Write a recursive function that takes a linked list as input and returns all...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Problem 1 Given a linked list of integers, write a function getUnique that removes all duplicates elements in the linked list and returns the new linked list of unique elements (The order does not ma...

    Problem 1 Given a linked list of integers, write a function getUnique that removes all duplicates elements in the linked list and returns the new linked list of unique elements (The order does not matter). Example: Input: 1-»2->3->1-2 Output: 1->2->3 public class Node f int iterm Node next; Node(int d) t item = d; next-null; ) import java.util.ArrayList; public class ExtraLab public static void main (String[] args)t PROBLEM 1 System.out.println("PROBLEM 1"); Node head new Node(1); head.next-new Node (2); head.next.next-new Node(3);...

  • iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains...

    iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains a loop. Print true if yes, false if not. Test by using the following code: LL<Integer> L = new LL<>(); for (int i = 1000; i > 0; i-=3) sl.add(i); try { L.insert(122, L.getNode(70), L.getNode(21)); if (L.detectLoop()) System.out.println("True"); else System.out.println("False."); } catch(Exception e){ e.printStackTrace(); } class Linkedlist<E>{ private static class Node<E>{ private E element; private Node<E> next; public Node(E e, Node<E> n){ element =...

  • Question 2 (3 points) Given the following singly linked list (a list with four nodes), what...

    Question 2 (3 points) Given the following singly linked list (a list with four nodes), what will be the value stored at the last node when the following operations are executed? head->1111-151->11011->1211 Node curr = head; while(curr next !=null) { curr.item = curritem-head. item; curr = cur next; اسرة Node newNode = new Node(8): curr.next = newNode: 23 O 12 OS O21 Question 3 (3 points) Given a recursive method as shown below, what is the return value for P(5)...

  • Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element...

    Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element stored at this node */ private int element; // reference to the element stored at this node /** A reference to the subsequent node in the list */ private Node next; // reference to the subsequent node in the list /** * Creates a node with the given element and next node. * * @param e the element to be stored * @param n...

  • In java Write a method public void printReverse() that prints the elements of a doubly linked...

    In java Write a method public void printReverse() that prints the elements of a doubly linked list in reverse. Write a method public void delete5FromTheEnd() which deletes the 5th element from end of the list. Note that if you reach the end then you have to reverse the direction of counting. In the main() method of the test class, create a randomly generated Doubly-Linked list of 10 Integers. Next, call the delete5FromTheEnd() method and print the lists iteratively until the...

  • In java Write a method public void printReverse() that prints the elements of a doubly linked...

    In java Write a method public void printReverse() that prints the elements of a doubly linked list in reverse. Write a method public void delete5FromTheEnd() which deletes the 5th element from end of the list. Note that if you reach the end then you have to reverse the direction of counting. In the main() method of the test class, create a randomly generated Doubly-Linked list of 10 Integers. Next, call the delete5FromTheEnd() method and print the lists iteratively until the...

  • Writing a method retainAll for Circular Doubly-Linked List: I am working on an assignment creating a...

    Writing a method retainAll for Circular Doubly-Linked List: I am working on an assignment creating a Circular Doubly Linked List and am having serious trouble creating a method retainAll. Here's the code, and my attempt. Initialization: public class CDoublyLinkedList {    private class Node {        private Object data; //Assume data implemented Comparable        private Node next, prev;        private Node(Object data, Node pref, Node next)        {            this.data = data;       ...

  • Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time...

    Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time complexity is omitted. Any methods/functions below could be changed into something different. I was thinking of changing the method of getting size of list and maybe change from numbers to letters for nodes. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null;...

  • Implement the following in java. 1. An insertAtBeginning(Node newNode) function, that inserts a node at the...

    Implement the following in java. 1. An insertAtBeginning(Node newNode) function, that inserts a node at the beginning(root) of the linked list. 2. A removeFromBeginning() function, that removes the node from the beginning of the linked list and assigns the next element as the new beginning(root). 3. A traverse function, that iterates the list and prints the elements in the linked list. For the insertAtBeginning(Node newNode) function: 1. Check if the root is null. If it is, just assign the new...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT