Challenge: Sort Values in a Stack
In this lesson, we will learn how to sort elements using a stack.
We'll cover the following
Problem Statement
Implement a function called sort_stack()
which takes a stack and sorts all of its elements in ascending order such that when they are popped and printed, they come out in ascending order. So the element that was pushed last to the stack has to be the smallest.
Input
A stack of integers.
Output
The stack with all its elements sorted in descending order.
Sample Input
stack = [23, 60, 12, 42, 4, 97, 2]
Sample Output
result = [97, 60, 42, 23, 12, 4, 2]
## 2 was the value last pushed
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.