In: Computer Science
compute the position of the last 5.0 in the list, counting as an offset from the end. if 5.0 is the LAST element, the position is 0. if 5.0 does not appear, return a negative number. you can write this using a loop or recursion, in any style, but you should only have one loop or recursive helper
Use a backward recursion.If the number does not appear, return the distance to the END of the list as a NEGATIVE number.
public class MyLinked {
static class Node {
public Node (double item, Node
next) { this.item = item; this.next = next; }
public double item;
public Node next;
}
int N;
public int positionOfLastFiveFromEnd () {
You can NOT modify the list or parameters, add fields to the node or list class, or add any methods/use any functions to the node class. Please use a helper and backward recursion.
import java.io.*;
public class MyLinked {
public static Node head;
static class Node{
public Node (double item, Node
next)
{
this.item =
item; this.next = next;
}
public double item;
public Node next;}
int N;
public int positionOfLastFiveFromEnd ()
{
Node
currNode = head;
N=0;
// Traverse
through the LinkedList
while (currNode!= null)
{ N-=1;
// if currNode value is 5.0 then counter
of
// N will start from 0 again and will reach
till
if
(currNode.item==5.0) {N=0;}
// Go to next node
currNode =
currNode.next;
}
// last N's position will
start from 0 ,
//then it will be decremented
by 1 until last node is reached.
return( N);
}
public static void main(String[] args)
{
/* Start with the empty
list. */
MyLinked list = new MyLinked();
Node d=new Node (7,null);
//making a last node with value equal to 5
Node c=new Node(5,d); //making a node with value equal
to 4
Node b=new Node(3,c); //making a node with value equal
to 3
Node a=new Node(2,b); //making a node with value equal
to 2
head=a;
int x =list.positionOfLastFiveFromEnd();// calling
function
System.out.print(x);
}
}