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

Write a method called getHiLo() that takes an Stack of Integers of any length as

ID: 3775187 • Letter: W

Question

Write a method called getHiLo() that takes an Stack of Integers of any length as its only parameter, and returns a new Stack of Integers that has a length of only 2. The top value in the new Stack that is returned is the highest value in the Stack that was passed, and the second value is the lowest value in the Stack that was passed. You can assume the Stack that is passed has at least one element in it, and you will leave it empty after the getHiLo() method is done.

You only have to write the method, not the entire class.

Explanation / Answer

Hi, Please find my implementation.

Please let me know in case of any issue.

public Stack<Integer> getHiLo(Stack<Integer> stack){

      

       // creating new Stack

       Stack<Integer> newStack = new Stack<Integer>();

      

       // initializing minimum and maximum with top element of input stack

       int max = stack.pop();

       int min = max;

      

       while(! stack.empty()){

          

           int item = stack.pop();

          

           if(item < min)

               min = item;

          

           if(item > max)

               max = item;

       }  

      

       // putting min and max in newStack

       newStack.push(min);

       newStack.push(max);

      

       return newStack;

   }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote