代码改变世界

reverse a stack in place using recursion

2010-10-02 23:09  wansishuang  阅读(231)  评论(0编辑  收藏  举报

Write a C Program to reverse a stack in place using recursion. You can only use the following ADT functions on stack: IsEmpty, IsFull, Push, Pop, Top
you can not use extra stack or any other data structure

 

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

template<typename T>
void reverse(stack<T>&s)
{
    if(s.empty()) return;
    T top = s.top();
    s.pop();
    reverse(s);
    push(s, top);
}

template<typename T>
void push(stack<T> &s, int key)
{
    if(s.empty())
    {
        s.push(key);
        return;
    }
    int top = s.top();
    s.pop();
    push(s, key);
    s.push(top);
}

int main()
{
    stack<int> s;
    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);
    s.push(5);

    reverse(s);

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