Write a program to sort a stack in ascending order(编写程序以升序对堆栈进行排序)
问题描述
有人可以帮忙看看我的代码吗?非常感谢你的帮助.输入堆栈是 [5, 2, 1, 9, 0, 10],我的代码给出了输出堆栈 [0, 9, 1, 2, 5, 10],9 不在正确的位置.
Can someone help look at my code, please? Thank you so much for your help. The input stack is [5, 2, 1, 9, 0, 10], my codes gave output stack [0, 9, 1, 2, 5, 10], 9 is not in the right position.
import java.util.*;
public class CC3_6 {
public static void main(String[] args) {
int[] data = {5, 2, 1, 9, 0, 10};
Stack<Integer> myStack = new Stack<Integer>();
for (int i = 0; i < data.length; i++){
myStack.push(data[i]);
}
System.out.println(sortStack(myStack));
}
public static Stack<Integer> sortStack(Stack<Integer> origin) {
if (origin == null)
return null;
if (origin.size() < 2)
return origin;
Stack<Integer> result = new Stack<Integer>();
while (!origin.isEmpty()) {
int smallest = origin.pop();
int remainder = origin.size();
for (int i = 0; i < remainder; i++) {
int element = origin.pop();
if (element < smallest) {
origin.push(smallest);
smallest = element;
} else {
origin.push(element);
}
}
result.push(smallest);
}
return result;
}
}
推荐答案
这是我的代码版本,非常简单易懂.
Here's my version of the code which is pretty straightforward to follow.
import java.util.Stack;
public class StackSorting {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(12);
stack.push(100);
stack.push(13);
stack.push(50);
stack.push(4);
System.out.println("Elements on stack before sorting: "+ stack.toString());
stack = sort(stack);
System.out.println("Elements on stack after sorting: "+ stack.toString());
}
private static Stack<Integer> sort(Stack<Integer> stack) {
if (stack.isEmpty()) {
return null;
}
Stack<Integer> sortedStack = new Stack<Integer>();
int element = 0;
while(!stack.isEmpty()) {
if (stack.peek() <= (element = stack.pop())) {
if (sortedStack.isEmpty()) {
sortedStack.push(element);
} else {
while((!sortedStack.isEmpty()) && sortedStack.peek() > element) {
stack.push(sortedStack.pop());
}
sortedStack.push(element);
}
}
}
return sortedStack;
}
}
这篇关于编写程序以升序对堆栈进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:编写程序以升序对堆栈进行排序
基础教程推荐
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01