颠倒栈中元素--栈的逆置
来源:互联网 发布:大学生衣服淘宝店铺 编辑:程序博客网 时间:2024/06/06 00:27
思路:
1.使用递归pop出栈中元素,直到栈中元素只剩下一个元素
2.当前第一次递归返回的时候,栈中有2个元素,我们再利用另一个递归函数putItem把两个元素逆置
3.以此递归下去,直到栈中元素全部逆置。
过程如下
1)1 , 2, 3, 4 第一个递归不断出栈,第一次满足返回条件时,栈中元素只有 1
2)回到第一个递归的上一层,利用putItem把 2 压入栈中,当putItem返回时,栈中元素为 2 1
3)继续回到第一个递归的上一层,利用putItem把 3 压入栈中,当putItem返回时,栈中元素为 3 2 1
4)继续回到第一个递归的上一层,利用putItem把 4 压入栈中,当putItem返回时,栈中元素为 4 3 2 1
5)至此递归结束
#include <iostream>#include <stack>using namespace std;stack<int> st;void putItem(stack<int> &st, int data){if (st.size() == 0){st.push(data);return;}int tmp = st.top();st.pop();putItem(st, data);st.push(tmp);}void reverseStack(stack<int> &st){if (st.size() == 1){return ;}int tmp = st.top();st.pop();reverseStack(st);putItem(st, tmp);}int main(){st.push(1);st.push(2);st.push(3);reverseStack(st);while(!st.empty()){printf("%d ", st.top());st.pop();}return 0;}
- 颠倒栈中元素--栈的逆置
- 颠倒List集合里的元素(利用栈)
- 递归算法颠倒栈中的元素
- 颠倒栈
- 颠倒栈
- 颠倒栈
- 颠倒栈
- 颠倒栈
- 颠倒栈
- 颠倒栈
- 颠倒栈
- 颠倒栈
- 颠倒栈
- 将数组元素颠倒的java代码
- C++实现的递归颠倒栈
- 栈的颠倒算法 递归实现
- 递归颠倒栈
- 递归颠倒栈
- 浅谈linux系统下常见的故障与处理方法
- WinRAR的注册破解
- JS 判断字符串包含
- 数据结构——顺序查找
- oracle服务开关软件
- 颠倒栈中元素--栈的逆置
- CI编码问题
- MongoDB数据表基本操作
- .net更改ip,dns等
- 解释析构函数为什么要声明成虚函数
- 快速理解VirtualBox的四种网络连接方式
- 对于Kernel panic - not syncing: No init found出错的解决办法
- CentOS 网络设置修改
- Xcode Svn 多人开发小设置