左神面试算法整理--栈的逆序
来源:互联网 发布:linux服务器架设书 编辑:程序博客网 时间:2024/06/16 00:35
算法思路:
建立两个栈,一个f,一个p。f实现找出栈中最底部的元素并返回。p利用递归和f函数,将从栈顶元素依次压入栈中实现逆序。
JAVA版
package problems_2017_07_26;
import java.util.Stack;
public class Problem_01_ReverseStackUsingRecursive {
public static void reverse(Stack<Integer> stack) {
if (stack.isEmpty()) {
return;
}
int i = getAndRemoveLastElement(stack);
reverse(stack);
stack.push(i);
}
public static int getAndRemoveLastElement(Stack<Integer> stack) {
int result = stack.pop();
if (stack.isEmpty()) {
return result;
} else {
int last = getAndRemoveLastElement(stack);
stack.push(result);
return last;
}
}
public static void main(String[] args) {
Stack<Integer> test = new Stack<Integer>();
test.push(1);
test.push(2);
test.push(3);
test.push(4);
test.push(5);
reverse(test);
while (!test.isEmpty()) {
System.out.println(test.pop());
}
}
}
C++版
int f(stack<int> a)
{
int result=a.top();
a.pop();
if(a.empty())
return result;
else
{
int last=f(a);
a.push(result);
return last;
}
}
void p(stack<int> a)
{
if(a.empty())
return ;
else
{
int last=f(a);
a.pop();
p(a);
a.push(last);
}
}
int main()
{
stack<int> result;
result.push(1);
result.push(2);
result.push(3);
result.push(4);
p(result);
for(int i=0;i<4;i++)
{
cout<<result.top();
result.pop();
}
cout<<endl;
system("pause");
return 0;
}
- 左神面试算法整理--栈的逆序
- 左神面试算法整理---单调栈
- 左神面试算法整理--并归求小和
- 左神面试算法整理--最大子串和
- 左神面试算法--哈希表
- 左神面试算法整理--二叉树前、中、后序遍历
- 左神面试算法整理--二叉搜索数最大拓扑结构
- 栈的逆序算法
- 面试算法题整理
- 算法面试-学习笔记-左旋转字符串
- 由“栈的逆序”谈谈递归算法
- 笔试面试算法经典--数组partition调整使数组的左部分单调有序
- 常见面试算法题整理
- 面试的算法2(C语言)(整理)
- 面试中经常出现的算法1(整理)
- 面试中经常出现的算法2(整理)
- 前端面试中常见的算法问题读后整理
- 前端面试中常见的算法问题读后整理
- database.net连接ORACL以及plsql连接oracle
- Robotframework / RIDE Win7安装步骤
- mysql数据库引擎常用面试总结
- Ubuntu 16.04 常用软件安装
- G
- 左神面试算法整理--栈的逆序
- 每天一点新姿势:spring事务的学习
- Python2和Python3之间的区别
- Python基础
- Struts2(三)-Struts2之文件的上传和下载
- spark机器学习构建回归模型
- mongoose mpromise被废弃警告,(node:3341) DeprecationWarning: Mongoose: mpromise (mongoose's default promis
- 【Java】断言中assertNotEquals与assertNotSame的区别
- thinkphp