题目:
一个栈中的类型为整形,现在想将该栈从顶到底按从小到大的顺序排序,只允许申请一个栈 除此之外,可以申请新的变量,但是不能申请额外的数据结构,如何完成排序。
思路:
设计一个cur变量,存放stack栈弹出的当前元素,和辅助栈help的栈顶元素进行比较,若大于辅助栈栈顶元素,则将辅助栈中元素一一弹出,压入stack栈中,若小于辅助栈栈顶元素,则将cur压入辅助栈中,知道stack栈为空,再将辅助栈一一弹出压入stack栈中,排序完成。
public class test1 { public void sortStack() { Stack<Integer> help = new Stack<>(); Stack<Integer> stack = new Stack<>(); while (!stack.isEmpty()) { int cur = stack.pop(); while (!help.isEmpty() && cur > help.peek()) { stack.push(help.pop()); } help.push(cur); while (!help.isEmpty()){ stack.push(help.pop()); } } } }