我需要写一个方法,压缩做以下操作;任何人都可以告诉我我做错了什么吗? - 堆栈
方法compress的目标是从堆栈s1中删除所有空元素。其余(非空) 元素应按照其初始顺序保留在s1上。辅助堆栈s2应作为 用于来自s1的元素的临时存储。在此方法计算结束时, 堆栈s2应具有与计算开始时相同的内容。请参阅方法 main以了解方法compress的预期行为的示例。
到目前为止我有;
import net.datastructures.ArrayStack;
import net.datastructures.Stack;
public class Stacks {
public static <E> void compress(Stack<E> S1, Stack<E> S2) {
int counter = 0;
while (!S1.isEmpty()) {
}
if (S1.top() == null) {
S1.pop();
} else if (S1.top() != null) {
S2.push(S1.pop());
counter++;
}
for (int i = counter; i < counter; i++) {
S2.push(S1.pop());
}
}
public static void main(String[] args) {
// test method compress
Stack<Integer> S1 = new ArrayStack<Integer>(10);
S1.push(2);
S1.push(null);
S1.push(null);
S1.push(4);
S1.push(6);
S1.push(null);
Stack<Integer> S2 = new ArrayStack<Integer>(10);
S2.push(7);
S2.push(9);
System.out.println("stack S1: " + S1);
// prints: "stack S1: [2, null, null, 4, 6, null]"
System.out.println("stack S2: " + S2);
// prints: "stack s2: [7, 9]"
compress(S1, S2);
System.out.println("stack S1: " + S1);
// should print: "stack S1: [2, 4, 6]"
System.out.println("stack S2: " + S2);
// should print: "stack S2: [7, 9]"
}
}
我想不通哪里出错,代码在压缩方法之前打印两行,然后不打印任何内容。
我想当你清理'S2'时,你需要执行'S1.push(S2.pop());' – 2013-02-23 20:58:19
你是否尝试在调试器中逐步调试代码? – millimoose 2013-02-23 20:58:40
此外,循环'while(!S1.isEmpty())'什么也不做,你只检查S1中的一个元素。 (除非这是一个错字) – millimoose 2013-02-23 20:59:42