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

JAVA /** * maxPosition returns the position of the maximum data in the LinkedLis

ID: 3781347 • Letter: J

Question

JAVA  

/**
   * maxPosition returns the position of the maximum data in the LinkedList.
   * The first position in the LinkedList is 0 and the last is size()-1.
   * If the list is empty you will need to return -1.
   * If there are duplicates, you can return any of the indices.
   *
   * Examples:
   * LinkedList : null ==> return -1
   * LinkedList : 2 --> 3 --> null ==> return 1
   * LinkedList : 6 --> 3 --> null ==> return 0
   * LinkedList : 2 --> -3 --> 2 --> null ==> return 0 or 2
   */

The code:
   public int maxPosition() {
       return 0; // TODO
   }

Explanation / Answer

public int maxPosition() {
  
   //suppose head is the root node and data is the value part of the node
   // Suppose the node in linkedlist is of type Node
   int pos=-1;
   int h;
   if(head==null)
   return -1;
   else
   {
       Node temp=head;
       pos=0; h= head.data;
       for(int i=1; i<size()-1; i++)
       {
           temp=temp.next;
           if(temp.data > h)
           {
               h=temp.data; // replace value of highest
               pos= i; // update the pos of highest accordingly
           }
       }
       return pos;
   }
  
}