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: 3782100 • 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

   */

Code I have is:

   public int maxPosition() {

       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;

   }

Explanation / Answer

Here is the modified method for you:

public int maxPosition() {
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++){//For loop will not work for linkedlist, especially the size() method.
while(temp->next != null) {   //If there is no next node to compare stop looping.

if(temp->next->data > h){   //next node value is greater than current value.
h=temp->next->data; // replace value of highest
hp = pos;   //Update highest position.
}
pos++; // update the pos to the next value.

}
  
}
return hp;   //Returns the highest position.
}