方法sortStack()
按降序排列未排序的堆栈。
但是,当我尝试将方法用于2个单独的堆栈时,第二个排序的堆栈将与第一个排序的堆栈合并。有人可以帮我解决我所缺少的吗?
static Stack<Integer> descending = new Stack<Integer>();
static Stack<Integer> tmpStack = new Stack<Integer>();
public static Stack<Integer> sortStack(Stack<Integer> input){
while(!input.isEmpty()) {
int tmp = input.pop();
while(!tmpStack.isEmpty() && tmpStack.peek() > tmp) {
input.push(tmpStack.pop());
}
tmpStack.push(tmp);
}
while(!tmpStack.isEmpty()) {
descending.push(tmpStack.pop());
}
return descending;
}
public static void main(String args[]){
Stack<Integer> A = new Stack<Integer>();
A.push(34);
A.push(3);
A.push(31);
System.out.println("unsorted: " + A);
Stack<Integer> C = sortStack(A);
System.out.println("sorted: " + C);
Stack<Integer> B = new Stack<Integer>();
B.push(1);
B.push(12);
B.push(23);
System.out.println("unsorted: " + B);
Stack<Integer> D = sortStack(B);
System.out.println("sorted: " + D);
}
输出
unsorted: [34, 3, 31]
sorted: [34, 31, 3]
unsorted: [1, 12, 23]
sorted: [34, 31, 3, 23, 12, 1]
答案 0 :(得分:0)
public static Stack<Integer> sortStack(Stack<Integer> stack) {
stack.sort(Comparator.reverseOrder());
return stack;
}
输出:
unsorted: [34, 3, 31]
sorted: [34, 31, 3]
unsorted: [1, 12, 23]
sorted: [23, 12, 1]
答案 1 :(得分:0)
将Stack<Integer> tmpStack = new Stack<Integer>();
声明为局部变量而不是类变量。
public static void main(String args[]){
Stack<Integer> A = new Stack<Integer>();
A.push(34);
A.push(3);
A.push(31);
System.out.println("unsorted: " + A);
Stack<Integer> C = sortStack(A);
//After this method call tmpStack will have [3, 31, 34]
System.out.println("sorted: " + C);
Stack<Integer> B = new Stack<Integer>();
B.push(1);
B.push(12);
B.push(23);
System.out.println("unsorted: " + B);
Stack<Integer> D = sortStack(B);
//After this method call tmpStack will have [34, 31, 3, 1, 12, 23]
//Here you are appending 1, 12, 23 values to existing tmpStack[3, 31, 34]
System.out.println("sorted: " + D);
}
解决方案:
将tmpStack
声明为局部变量。
此外,如果您想按降序排序,则无需添加额外的代码
while(!tmpStack.isEmpty()) {
descending.push(tmpStack.pop());
}
您只需将条件更改为'>'或'<'
升序:while(!tmpStack.isEmpty() && tmpStack.peek() > tmp) {}
取消顺序:while(!tmpStack.isEmpty() && tmpStack.peek() < tmp) {}
public static Stack<Integer> sortStack(Stack<Integer> input) {
Stack<Integer> tmpStack = new Stack<Integer>();
while (!input.isEmpty()) {
int tmp = input.pop();
while (!tmpStack.isEmpty() && tmpStack.peek() < tmp) {
input.push(tmpStack.pop());
}
tmpStack.push(tmp);
}
//while (!tmpStack.isEmpty()) {
// descending.push(tmpStack.pop());
//}
return tmpStack;
}