双栈排序

来源:互联网 发布: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
原创粉丝点击