VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-insert-an-element-at-the-bottom-of-a-stack/

⇱ Program to insert an element at the Bottom of a Stack - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to insert an element at the Bottom of a Stack

Last Updated : 15 Apr, 2025

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 7

Input: x = 17
s = 1 <- (Top)
      12
    34
     47
    15
Output: 1 12 34 47 15 17

Using Temporary Stack - O(n) time and O(n) space

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.


Output
1 2 3 4 5 7 

Using Recursion - O(n) time and O(n) space

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.


Output
1 2 3 4 5 7
Comment
Article Tags: