一个栈中的元素都是整形,现在想要将该栈从顶到底按从大到小的顺序排序,只许申请一个栈。除此之外,可以申请新的变量,但是不能申请额外的数据结构。如何实现排序?
import java.util.Stack;
public class SortStackByStack {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(2);
stack.push(1);
stack.push(3);
stack.push(-1);
stack.push(100);
stack.push(8);
stack = sortStackByStack(stack);
while (!stack.isEmpty()){
System.out.print(stack.pop() + " ");
}
}
private static Stack<Integer> sortStackByStack(Stack<Integer> stack){
Stack<Integer> help = new Stack<>();
while (!stack.isEmpty()){
int cur = stack.pop();
while (!help.isEmpty() && help.peek() < cur){
//1.将help中更小的数先压回stack中,下次再压回来
stack.push(help.pop());
}
//2.help压入当前的值
help.push(cur);
}
while (!help.isEmpty()){
stack.push(help.pop());
}
return stack;
}
}