数据结构练习(29)用递归颠倒栈
2012-12-17 21:28
183 查看
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); } }
其实上述代码什么也没做,模仿了栈的逻辑,不断的保护数据,缩小规模。
在上述代码逻辑里面试图加入自己的代码,从而改变其固有稳定的代码逻辑,这才是利用递归真正要做的东西。
关于这方面,总感觉还欠缺点思考,欠缺点总结,还需要不断的继续实践啊。
相关文章推荐
- 数据结构练习(39)二叉树前中后序遍历的非递归实现
- 数据结构 树的遍历(递归遍历练习)
- 数据结构--递归练习
- 数据结构之递归小练习(定义,阶乘,求和,汉诺塔)
- 递推递归练习G
- ACM-递归递推练习K- 们--加强斐波那契
- 递推递归练习I - 蟠桃记
- 递推递归练习第c题解析
- ACM递推递归练习C递归的函数
- 递推递归练习N青蛙过河
- 二叉树后序遍历非递归的三种写法 (数据结构)
- 练习,递归求奇数的积
- 递归递推练习 E
- 递归递推练习 M
- 数据结构-循环和递归
- SDUTOJ 2138 图结构练习——BFSDFS——判断可达性(以边表为数据结构)
- 递归递推练习–K11
- 【备战蓝桥杯】【递归】【C语言】【BASIC-22基础练习 FJ的字符串】
- 基本功练习_2_23之递归n!
- 蓝桥杯C语言基础练习 FJ的字符串(递归)