双栈排序
来源:互联网 发布:caffe的test iter 编辑:程序博客网 时间:2024/06/06 16:27
请编写一个程序,按升序对栈进行排序(即最大元素位于栈顶),要求最多只能使用一个额外的栈存放临时数据,但不得将元素复制到别的数据结构中。
给定一个int[] numbers(C++中为vector<int>),其中第一个元素为栈顶,请返回排序后的栈。请注意这是一个栈,意味着排序过程中你只能访问到第一个元素。
测试样例:
[1,2,3,4,5]
返回:[5,4,3,2,1]
代码如下:
import java.util.*;public class TwoStacks { public ArrayList<Integer> twoStacksSort(int[] numbers) { Stack<Integer> A =new Stack<Integer>();Stack<Integer> B =new Stack<Integer>();ArrayList<Integer> list =new ArrayList<Integer>();for (int i = 0; i < numbers.length; i++) { A.push(numbers[i]);}while(!A.isEmpty()){int temp =A.pop();//为什么要用&&同时判断呢,是因为如果只有!B.isEmpty()的话再用if判断 B.peek()>temp//就会进入死循环当!B.isEmpty()符合当前条件的话 while(!B.isEmpty() && B.peek()>temp){ A.push(B.pop()); } B.push(temp);}while (!B.isEmpty()) { list.add(B.pop());}return list; }}
0 0
- [NOIP2008]双栈排序
- NOIP2008 双栈排序
- sicily双栈排序
- 双栈排序
- [noip2008]双栈排序
- 双栈排序
- Codevs1170 双栈排序
- 双栈排序
- 双栈排序
- 双栈排序
- 双栈排序
- 双栈排序
- 双栈排序
- 双栈排序
- P1155 双栈排序
- 1002. 双栈排序
- 双栈排序
- 双栈排序
- OIDC–基于OAuth2的下一代身份认证授权协议
- JSP02
- ssm(spring+springMVC+Mybatis)框架 集成Quartz(定时任务框架)
- Mapreduce和HBase新版本整合之WordCount计数案例
- 文章标题
- 双栈排序
- TimesTen的操作系统,数据库和虚拟化软件支持列表
- Leetcode 84. Largest Rectangle in Histogram & 85. Maximal Rectangle
- Java 多线程(六) synchronized关键字详解
- 基于AT91SAM9261EK的嵌入式Linux2.6.32+Yaffs2 根文件系统移植成功
- Spark Streaming+Kafka+Hive+JSON实时增量计算示例
- eclipse安装maven插件
- POJ 1039Pipe(直线相交)
- Dhroid框架六大组件之Ioc容器【下】