Skip to content
Related Articles

Related Articles

Improve Article

Program to insert an element at the Bottom of a Stack

  • Difficulty Level : Basic
  • Last Updated : 02 Jul, 2021

Given a stack S and an integer N, the task is to insert N at the bottom of the stack.

Examples:

Input: N = 7
S = 1 <- (Top)
      2
     3
     4
     5
Output: 1 2 3 4 5 7

Input: N = 17
S = 1 <- (Top)
     12
     34
     47
     15
Output: 1 12 34 47 15 17

Naive Approach: The simplest approach would be to create another stack. Follow the steps below to solve the problem:



  1. Initialize a stack, say temp.
  2. Keep popping from the given stack S and pushing the popped elements into temp, until the stack S becomes empty.
  3. Push N into the stack S.
  4. Now, keep popping from the stacktemp and push the popped elements into the stack S, until the stack temp becomes empty.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to insert an element
// at the bottom of a given stack
void insertToBottom(stack<int> S, int N)
{
    // Temporary stack
    stack<int> temp;
 
    // Iterate until S becomes empty
    while (!S.empty()) {
 
        // Push the top element of S
        // into the stack temp
        temp.push(S.top());
 
        // Pop the top element of S
        S.pop();
    }
 
    // Push N into the stack S
    S.push(N);
 
    // Iterate until temp becomes empty
    while (!temp.empty()) {
 
        // Push the top element of
        // temp into the stack S
        S.push(temp.top());
 
        // Pop the top element of temp
        temp.pop();
    }
 
    // Print the elements of S
    while (!S.empty()) {
        cout << S.top() << " ";
        S.pop();
    }
}
 
// Driver Code
int main()
{
    // Input
    stack<int> S;
    S.push(5);
    S.push(4);
    S.push(3);
    S.push(2);
    S.push(1);
 
    int N = 7;
 
    insertToBottom(S, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.Stack;
 
class GFG{
 
// Function to insert an element
// at the bottom of a given stack
static void insertToBottom(Stack<Integer> S, int N)
{
     
    // Temporary stack
    Stack<Integer> temp = new Stack<>();
 
    // Iterate until S becomes empty
    while (!S.empty())
    {
 
        // Push the top element of S
        // into the stack temp
        temp.push(S.peek());
 
        // Pop the top element of S
        S.pop();
    }
 
    // Push N into the stack S
    S.push(N);
 
    // Iterate until temp becomes empty
    while (!temp.empty())
    {
 
        // Push the top element of
        // temp into the stack S
        S.push(temp.peek());
 
        // Pop the top element of temp
        temp.pop();
    }
 
    // Print the elements of S
    while (!S.empty())
    {
        System.out.print(S.peek() + " ");
        S.pop();
    }
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given Binary Tree
    Stack<Integer> S = new Stack<>();
    S.push(5);
    S.push(4);
    S.push(3);
    S.push(2);
    S.push(1);
 
    int N = 7;
 
    insertToBottom(S, N);
}
}
 
// This code is contributed by abhinavjain194

Python3




# Python3 program for the above approach
 
# Function to insert an element
# at the bottom of a given stack
def insertToBottom(S, N):
     
    # Temporary stack
    temp = []
 
    # Iterate until S becomes empty
    while (len(S) != 0):
 
        # Push the top element of S
        # into the stack temp
        temp.append(S[-1])
 
        # Pop the top element of S
        S.pop()
 
    # Push N into the stack S
    S.append(N)
 
    # Iterate until temp becomes empty
    while (len(temp) != 0):
 
        # Push the top element of
        # temp into the stack S
        S.append(temp[-1])
 
        # Pop the top element of temp
        temp.pop()
 
    # Print the elements of S
    while (len(S) != 0):
        print(S[-1], end = " ")
        S.pop()
 
# Driver Code
if __name__ == "__main__":
 
    # Input
    S = []
    S.append(5)
    S.append(4)
    S.append(3)
    S.append(2)
    S.append(1)
 
    N = 7
 
    insertToBottom(S, N)
 
# This code is contributed by ukasp

C#




// C# program for the above approach
 
using System;
using System.Collections;
 
public class GFG {
 
    // Function to insert an element
    // at the bottom of a given stack
    static void insertToBottom(Stack S, int N)
    {
 
        // Temporary stack
        Stack temp = new Stack();
 
        // Iterate until S becomes empty
        while (S.Count != 0) {
 
            // Push the top element of S
            // into the stack temp
            temp.Push(S.Peek());
 
            // Pop the top element of S
            S.Pop();
        }
 
        // Push N into the stack S
        S.Push(N);
 
        // Iterate until temp becomes empty
        while (temp.Count != 0) {
 
            // Push the top element of
            // temp into the stack S
            S.Push(temp.Peek());
 
            // Pop the top element of temp
            temp.Pop();
        }
 
        // Print the elements of S
        while (S.Count != 0) {
            Console.Write(S.Peek() + " ");
            S.Pop();
        }
    }
 
    // Driver code
    static public void Main()
    {
 
        // Given Binary Tree
        Stack S = new Stack();
        S.Push(5);
        S.Push(4);
        S.Push(3);
        S.Push(2);
        S.Push(1);
 
        int N = 7;
 
        insertToBottom(S, N);
    }
}
 
// This code is contributed by Dharanendra L V.

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to insert an element
// at the bottom of a given stack
function insertToBottom(S, N)
{
    // Temporary stack
    var temp = [];
 
    // Iterate until S becomes empty
    while (S.length!=0) {
 
        // Push the top element of S
        // into the stack temp
        temp.push(S[S.length-1]);
 
        // Pop the top element of S
        S.pop();
    }
 
    // Push N into the stack S
    S.push(N);
 
    // Iterate until temp becomes empty
    while (temp.length!=0) {
 
        // Push the top element of
        // temp into the stack S
        S.push(temp[temp.length-1]);
 
        // Pop the top element of temp
        temp.pop();
    }
 
    // Print the elements of S
    while (S.length!=0) {
        document.write( S[S.length-1] + " ");
        S.pop();
    }
}
 
// Driver Code
 
// Input
var S = [];
S.push(5);
S.push(4);
S.push(3);
S.push(2);
S.push(1);
var N = 7;
insertToBottom(S, N);
 
</script>
Output: 
1 2 3 4 5 7

 

Time Complexity: O(N)
Auxiliary Space: O(N)

Efficient Approach: Instead of using a temporary stack, the implicit stack can be used through recursion. Follow the steps below to solve the problem: 

  1. Define a recursion function that accepts the stack S and an integer as parameters and returns a stack.
  2. Base case to be considered is if the stack is empty. For this scenario, push N into the stack and return it.
  3. Otherwise, remove the top element of S and store it in a variable, say X.
  4. Recurse again using the new stack
  5. Push X into S.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to use implicit stack
// to insert an element at the bottom of stack
stack<int> recur(stack<int> S, int N)
{
    // If stack is empty
    if (S.empty())
        S.push(N);
 
    else {
 
        // Stores the top element
        int X = S.top();
 
        // Pop the top element
        S.pop();
 
        // Recurse with remaining elements
        S = recur(S, N);
 
        // Push the previous
        // top element again
        S.push(X);
    }
    return S;
}
 
// Function to insert an element
// at the bottom of stack
void insertToBottom(
    stack<int> S, int N)
{
 
    // Recursively insert
    // N at the bottom of S
    S = recur(S, N);
 
    // Print the stack S
    while (!S.empty()) {
        cout << S.top() << " ";
        S.pop();
    }
}
 
// Driver Code
int main()
{
    // Input
    stack<int> S;
    S.push(5);
    S.push(4);
    S.push(3);
    S.push(2);
    S.push(1);
 
    int N = 7;
 
    insertToBottom(S, N);
 
    return 0;
}

Python3




# Python3 program for the above approach
      
# Recursive function to use implicit stack
# to insert an element at the bottom of stack
def recur(S, N):
     
    # If stack is empty
    if (len(S) == 0):
        S.append(N)
     
    else:
         
        # Stores the top element
        X = S[-1]
         
        # Pop the top element
        S.pop()
         
        # Recurse with remaining elements
        S = recur(S, N)
         
        # Push the previous
        # top element again
        S.append(X)
     
    return S
 
# Function to insert an element
# at the bottom of stack
def insertToBottom(S, N):
     
    # Recursively insert
    # N at the bottom of S
    S = recur(S, N)
     
    # Print the stack S
    while (len(S) > 0):
        print(S.pop(), end = " ")
 
# Driver code
 
# Input
S = []
S.append(5)
S.append(4)
S.append(3)
S.append(2)
S.append(1)
 
N = 7
 
insertToBottom(S, N)
 
# This code is contributed by avanitrachhadiya2155

Javascript




<script>
    // Javascript program for the above approach
     
    // Recursive function to use implicit stack
    // to insert an element at the bottom of stack
    function recur(S, N)
    {
        // If stack is empty
        if (S.length == 0)
            S.push(N);
 
        else {
 
            // Stores the top element
            let X = S[S.length - 1];
 
            // Pop the top element
            S.pop();
 
            // Recurse with remaining elements
            S = recur(S, N);
 
            // Push the previous
            // top element again
            S.push(X);
        }
        return S;
    }
 
    // Function to insert an element
    // at the bottom of stack
    function insertToBottom(S, N)
    {
 
        // Recursively insert
        // N at the bottom of S
        S = recur(S, N);
 
        // Print the stack S
        while (S.length > 0) {
            document.write(S[S.length - 1] + " ");
            S.pop();
        }
    }
     
    // Input
    let S = [];
    S.push(5);
    S.push(4);
    S.push(3);
    S.push(2);
    S.push(1);
  
    let N = 7;
  
    insertToBottom(S, N);
 
// This code is contributed by suresh07.
</script>
Output: 
1 2 3 4 5 7

 

Time Complexity: O(N)  
Auxiliary Space: O(1)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :