编写程序以升序对堆栈进行排序
有人可以帮忙看看我的代码吗?非常感谢你的帮助.输入堆栈是 [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;
}
}
相关文章