Reversing stack


#include<iostream>
#include<stack>
using namespace std;

void push_at_end(stack<int> &s,int num)
{
    if(s.empty())
    {
        s.push(num);
        return;
    }
    int element = s.top();
    s.pop();
    push_at_end(s,num);
    s.push(element);
}

void reverse(stack<int> &s)
{
    if(s.empty())
        return;
    int num = s.top();
    s.pop();
    reverse(s);
    push_at_end(s,num);
}

int main()
{
    int arr[]={1,4,6,8,2,5,10,12,14};
    stack<int> s;

    for(int i=0;i<9;i++)
    {
        s.push(arr[i]);
    }
    reverse(s);
    for(int i=0;i<9;i++)
    {
        cout<<s.top()<<" ";
        s.pop();
    }
    return 0;
}

Comments

Popular Posts