所以我正在处理这个代码,用户在方法xify(x)中输入一个int数组x。然后应该返回每个元素的数量。因此,如果x
是数组[4, 2, 3]
,我们应该返回标题列表:4 4 4 4 2 2 3 3 3
。
然而,看起来我的方法只返回一个空列表。我似乎无法追踪问题所在。下面我提供了我的xify()
方法,以及一个名为add的辅助方法,它将节点添加到列表中。
public static Node<Integer> xify(int[] x){
Node<Integer> result = new Node<>(null, null);
int counter=0;
int length=x.length;
while(counter<length){ //loop through the array
while(x[counter]!=0){ //take each element, add it to the list * int of the elem
add(result,x[counter]);
x[counter]=x[counter]-1;}
counter++;
}
return result;
}
帮手方法:
public static<T> void add(Node<T> list, T element){
while(list.getNext()!=null){
list=list.getNext();
}
list.setNext(new Node<>(element, null));
}
我的算法出了什么问题?
P.S你可能已经看到,它正在使用泛型,因为这是我目前正在学习的东西。
我如何称呼它:
System.out.println(xify(array));
System.out.println(toString(xify(array)));
答案 0 :(得分:1)
在您的主要代码中,您将方法调用两次,但您的方法具有破坏性:
x[counter]=x[counter]-1;
调用后,您的数组包含全零。所以第二个调用将(正确)产生一个空列表。
最简单的“修复”是调用一次:
Node<Integer> result = xify(array);
System.out.println(result);
System.out.println(toString(result)); // not sure what this does anyway?
更好的解决方法是不破坏你传入的内容。如果你在现实生活中摧毁这样的数据,其他开发人员会追捕你并扼杀你的利益(当然,比喻说......)。