Insert at the end of stack

Problem Statement:

You are given an element, you need to insert it at the end of the stach without using any data structure.

Solution

Solution is very simple. Here we need to use recursion.

Untill we reach at the end of the stack, we will take a temp variable to pop the element.

Then we reach the end of the stack, we insert the element and then push all the previously stored elements.

Solution in C++

#include <algorithm>  
//visit www.ProDeveloperTutorial.com for 450+ solved questions  
#include <iostream>    
#include <string>
#include <queue>
#include <vector>
#include <stack> 

using namespace std;

void display_stack(stack <int> s)
{
    stack<int> temp;
    while (s.empty() == false)
    {
        temp.push(s.top());
        s.pop();
    }   
 
    while (temp.empty() == false)
    {
        int t = temp.top();
        cout << t << " ";
        temp.pop();
 
        // restore to original stack
        s.push(t);  
    }
}

void insert_at_bottom(stack <int> &s, int x)
{

    if(s.empty())
        s.push(x);

    else
    {

        int a = s.top();
        s.pop();
        insert_at_bottom(s, x);

        s.push(a);
    }
}
 
int main ()
{
    stack <int> s;
    s.push(10);
    s.push(20);
    s.push(30);
    s.push(40);
 
 
    cout << "The stack is : ";
    display_stack(s);
 
    cout << "\ns.size() : " << s.size(); 
 
    insert_at_bottom(s, 50);

    cout << "\nThe stack is : ";
    display_stack(s);
 
    return 0;
}

Output:

The stack is : 10 20 30 40
s.size() : 4
The stack is : 50 10 20 30 40

 

 

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *