一个栈中的元素都是整形,现在想要将该栈从顶到底按从大到小的顺序排序,只许申请一个栈。除此之外,可以申请新的变量,但是不能申请额外的数据结构。如何实现排序?
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;
}
}
本文介绍了一种使用辅助栈进行栈内元素排序的算法,通过不断比较和压栈操作,实现了从顶到底按从大到小顺序排列的目标。此方法仅使用一个额外栈,未引入其他数据结构。
2571

被折叠的 条评论
为什么被折叠?



