Challenge: Sort the Values in a Stack

Given a stack, can you sort all its values in an ascending way? A solution is placed in the "solution" section to help you, but we would suggest you try to solve it on your own first.

Problem Statement #

In this problem, you have to implement the void sortStack(Stack<Integer> stack) method, which will take an Integer type stack and sort all its elements in ascending order. An illustration is also provided for your understanding.

Method Prototype #

void sortStack(Stack<Integer> stack)

Output #

It returns an Integer type Stack with all its elements sorted in ascending order

Sample Input #

stack = {23,60,12,42,4,97,2}

Sample Output #

result = {2,4,12,23,42,60,97}

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.