【题目】
一个栈中的元素的类型为整形,现在想将该栈从顶到底按从小到大的顺序排序,只许申请一个栈。除此之外,可以申请新的变量,但是不能申请额外的数据结构,如何完成排序。
【代码】
private void sortStackByStack(Stack<Integer> stack) {
Stack<Integer> helper = new Stack<>();
while (!stack.isEmpty()) {
Integer value = stack.pop();
while (!helper.isEmpty() && value < helper.peek()) {
stack.push(helper.pop());
}
helper.push(value);
}
while (!helper.isEmpty()) {
stack.push(helper.pop());
}
}
最后
以上就是昏睡麦片最近收集整理的关于11.用一个栈实现另一个栈的排序的全部内容,更多相关11.用一个栈实现另一个栈内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复