![]() |
VOOZH | about |
Given a stack s containing n integers and an integer x, the task is to insert the element x at the bottom of the stack.
Examples:
Input: x = 7
s = 1 <- (Top)
2
3
4
5
Output: 1 2 3 4 5 7Input: x = 17
s = 1 <- (Top)
12
34
47
15
Output: 1 12 34 47 15 17
First, we pop all the elements from the original stack and push them onto a temporary stack. This essentially reverses the order of elements from the original stack.
Then, we push the new element at the bottom of the original stack by adding it to the now-empty stack.
After inserting the new element, we push all elements from the temporary stack back onto the original stack to restore the original order.
1 2 3 4 5 7
We one by one remove stack elements and hold these elements in the recursion call stack. Once the stack becomes empty, we push the given element x into the stack and then one by one push the elements held in the recursion call stack.
1 2 3 4 5 7