In JAVA Recurrsion Methods For exercises 16 to 19 assume we

In JAVA

Recurrsion Methods

For exercises 16 to 19 assume we have a sorted linked list of Integer. The start of the linked list is referenced by values which, of course, is of type LLNode<Integer>. For example purposes, assume values points to a list containing 3, 6, 6, 9, 12, 15, 18, 19, 19, and 20. You can and should assume the list in question is sorted in nondecreasing order. For each of these exercises you should also create a driver application that demonstrates that your new method operates correctly.

16.Write a recursive method numEvens(LLNode<Integer> list) that returns how many even numbers are contained in list. For our example list numEvens(values) would return 5 (the even numbers are 6, 6, 12, 18, and 20).

17.Write a recursive method contains(int target, LLNode<Integer> list) that returns true if list contains target and false otherwise. For our example list contains(15, values) would return true while contains(10, values) would return false.

18.Write a recursive method remove(int target, LLNode<Integer> list) that removes all occurrences of target from list and returns a reference to the new list. For our example list the statement

values = remove(6, values);

would result in values referencing the list containing 3 9 12 15 18 19 19 and 20. If target is not contained in list then the list remains unchanged.

Solution

Hi, I have answered first two questions.

Please repost others in separate post.

Please let me know in cse of any issue in first two question.


int numEvens(LLNode<Integer> list){
  
   // Base Case
   if(list == null)
       return 0;
   if(list.getData()%2 == 0) // if curren node contains even number then call recursively for other nodes add 1
       return 1 + numEvens(list.getNext());
   else
       return 1 + numEvens(list.getNext());
}  

boolean contains(int target, LLNode<Integer> list){
  
   if(list == null)
       return false;

   if(target == list.getData())
       return true;
   else
       return contains(target, list.getNext());
}

In JAVA Recurrsion Methods For exercises 16 to 19 assume we have a sorted linked list of Integer. The start of the linked list is referenced by values which, of

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site