Reverse a stack using standard stack operations like push(), pop(), isEmpty()

#include <stack>
#include <iostream>

using namespace std;

typedef stack<int> Stack;

struct Node
{
int d;
Node *prev;
};

void push(Stack &s, Node *p)
{
if(!p) return;

push(s, p->prev);

s.push(p->d);

}


void reverse(Stack &s, Node *p)
{
if(!s.empty())
{
Node n = {s.top(), p};

s.pop();

reverse(s, &n);
}
else
{
push(s, p);
}
}


int main()
{
Stack s;
int n;

cin >> n;

for(int i = 0; i < n; i++)
s.push(i);

reverse(s, NULL);


while(!s.empty())
{
cout<<s.top()<<" ";
s.pop();
}

cout<<endl;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s