数据结构练习(29)用递归颠倒栈

http://zhedahht.blog.163.com/blog/static/25411174200943182411790/

思路:

为了用递归而用递归吧。总之,递归很强大,对于理解递归还是很不错的例子。

#include <stack>
using namespace std;

template <typename T>
void top2bottom(stack<T>& nstack, T element)
{
    if (nstack.empty())
        nstack.push(element);
    else
    {
        T e = nstack.top();
        nstack.pop();
        top2bottom(nstack, element);
        nstack.push(e);
    }
}

template <typename T> 
void ReverseStack(stack<T>& nstack)
{
    if (!nstack.empty())
    {
        T top = nstack.top();
        nstack.pop();
        ReverseStack(nstack);
        top2bottom(nstack, top);
    }
}

int main()
{
    stack<int> nstack;
    for (int i = 0; i < 10; ++i)
        nstack.push(static_cast<int>(i));
    ReverseStack(nstack);
    return 0;
}

 反思:

void recursive(stack<int>& s)
{
    if (!s.empty())
        int t = s.top();
        s.pop();
        recursive(s);
        s.push(t);
    }
}

其实上述代码什么也没做,模仿了栈的逻辑,不断的保护数据,缩小规模。

在上述代码逻辑里面试图加入自己的代码,从而改变其固有稳定的代码逻辑,这才是利用递归真正要做的东西。

关于这方面,总感觉还欠缺点思考,欠缺点总结,还需要不断的继续实践啊。

posted @ 2012-12-17 21:28  kedebug  阅读(296)  评论(0编辑  收藏  举报