【C语言】递归实现栈的逆序及排序
2015-11-29 15:40
561 查看
一、栈逆序
二、栈排序
void Move_bottom_top(stack<int>&s)//把栈底元素移动到栈顶位置 { if (s.empty()) { return; } int top1 = s.top(); s.pop(); if (!s.empty()) { Move_bottom_top(s); int top2 = s.top(); s.pop(); s.push(top1); s.push(top2); return; } s.push(top1); } void Reverse(stack<int>&s)//栈逆转 { if (s.empty()) { return; } Move_bottom_top(s); int top = s.top(); s.pop(); Reverse(s);//递归处理子栈 s.push(top); }
二、栈排序
void Move_max_top(stack<int>&s)//把最大的数弄到栈顶位置 { if (s.empty()) { return; } int top1 = s.top(); s.pop(); if (!s.empty()) { Move_max_top(s); int top2 = s.top(); if (top1 < top2) { s.pop(); s.push(top1); s.push(top2); return; } } s.push(top1); } void Sort(stack<int>&s) { if (s.empty()) { return; } Move_max_top(s); int top = s.top(); s.pop(); Sort(s);//递归处理子栈 s.push(top); }
相关文章推荐
- for循环 数组下标越界导致死循环
- c++11中的using关键字
- 编译原理(七) 算符优先分析法(构造算符优先关系表算法及C++实现)
- c++11中decltype的妙用
- bitset应用---产生1万个不重复的随机数
- c++11中的智能指针
- c++模板实现多参数任意传 - 类实现
- effective c++ 笔记之static_cast
- vs2008 dlib编译问题USER_ERROR__missing_dlib_all_source_cpp_file__OR__inconsistent_use_of_DEBUG_or_ENABLE
- 【C++】满二叉树与完全二叉树的区别及判断
- C++引用方式实现两个值的互换
- C++运算符重载
- C++抛出异常与传递参数的区别
- C++抛出异常与传递参数的区别
- C++【线程同步】-临界区同步
- c/c++进制转换
- C++的chrono、ratio和ctime等头文件
- leetcode Search a 2D Matrix
- C语言命名空间
- c语言字符数组与字符串的使用详解