**功能:将该栈排序
要求:只允许申请一个栈,不许用其他的数据结构**
stack —-cur—- help
- if(cur小于等于help的栈顶元素,则直接将cur压入help)
- else(弹出help的中的元素压入stack,直到cur小于等于help弹出的元素)
- 将cur压入help
- 直到stack中为空,将help压回stack
public static void sortStackByStack(Stack<Integer> stack) {
Stack<Integer> help = new Stack<Integer>();
while (!stack.isEmpty()) {
int cur = stack.pop();
while (!help.isEmpty() && help.peek() > cur) {
stack.push(help.pop());
}
help.push(cur);
}
while (!help.isEmpty()) {
stack.push(help.pop());
}
}
栈排序算法
本文介绍了一种使用辅助栈进行栈排序的方法。该算法仅允许使用一个额外的栈,并且不允许使用其他数据结构。通过不断地比较和交换操作,最终实现栈内元素的升序排列。
4114

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



