题目一:

  请编写一个程序,按升序对栈进行排序(即最大元素位于栈顶),要求最多只能使用一个额外的栈存放临时数据,但不得将元素复制到别的数据结构中。给定一个int[] numbers,其中第一个元素为栈顶,请返回排序后的栈。请注意这是一个栈,意味着排序过程中你只能访问到第一个元素。
  测试样例:[1,2,3,4,5]  返回:[5,4,3,2,1]。

  思路:这道题目很考验逻辑思维能力。将要排序的栈记为source,申请的辅助栈记为target。在source上执行pop操作,弹出的元素记为cru。   如果cru大于或等于target的栈顶元素,则将cru直接压入target。  如果cru小于target的栈顶元素,则将target的元素逐一弹出,逐一压入source,直到cru大于或等于target的栈顶元素,再将cru压入target。一直执行以上操作,直到source中的全部元素压入到target,最后返回target,完成排序。

 1 import java.util.Stack;
 2 
 3 public class StackSort {
 4     public static void main(String[] args) {
 5         StackSort obj = new StackSort();
 6         obj.twoStacksSort(new int[] { 8, 2, 3, 4, 5 });  // 输出 8 5 4 3 2
 7     }
 8 
 9     public void twoStacksSort(int[] numbers) {
10         // 初始化原始栈
11         Stack<Integer> source = new Stack<>();
12         for (int i = numbers.length - 1; i >= 0; i--) {
13             source.push(numbers[i]);
14         }
15 
16         Stack<Integer> target = twoStacksSort(source);
17         while (!target.isEmpty()) {
18             System.out.println(target.pop());
19         }
20     }
21 
22     public Stack<Integer> twoStacksSort(Stack<Integer> source) {
23 
24         Stack<Integer> target = new Stack<>();
25         sortToTarget(source, target);
26 
27         return target;
28     }
29 
30     private void sortToTarget(Stack<Integer> source, Stack<Integer> target) {
31         while (!source.empty()) {
32             int v1 = source.pop(); // 揭开盖子
33             if (target.empty()) {
34                 target.push(v1);
35             } else {
36                 int v2 = target.peek();
37                 if (v1 >= v2) { // 盖子大,直接放入
38                     target.push(v1);
39                 } else { // 盖子小,把大的先回收
40                     source.push(target.pop());
41                     // 直到有盖子的容身之所
42                     while (!target.empty() && v1 < target.peek()) {
43                         source.push(target.pop());
44                     }
45                     target.push(v1);
46                 }
47             }
48         }
49     }
50 }
View Code

相关文章: