Write a method called getHiLo that takes an Stack of Integer
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.
Solution
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;
}


