将一个栈内的元素排序,只能再使用一个辅助的栈,不能再使用其他数据结构
import java.util.ArrayList;
import java.util.Stack;
public class Main {
public ArrayList<Integer> solve(int[] arr) {
Stack<Integer> source = new Stack<>();
for (int num : arr) {
source.push(num);
}
Stack target = sort(source);
ArrayList res = new ArrayList();
for (Object element : target) {
res.add(element);
}
return res;
}
private Stack sort(Stack<Integer> source) {
Stack<Integer> help = new Stack<>();
while (!source.isEmpty()) {
int t = source.pop();
if (!help.isEmpty()) {
if (t < help.peek()) {
while (!help.isEmpty() && t < help.peek()) {
source.push(help.pop());
}
}
}
help.push(t);
}
return help;
}
public static void main(String[] args) {
int arr[] = {4, 6, 22, 77, 5, 56, 555, 1, 3, 55, 23};
ArrayList<Integer> solve = new Main().solve(arr);
for (Integer integer : solve) {
System.out.print(integer + " ");
}
}
}