所以我正在编写这段代码,其中用户将 int 数组 x 输入到方法 xify(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)));
最佳答案
在你的主代码中,你调用你的方法两次,但你的方法是破坏性:
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?
更好的解决办法是不要破坏你传入的内容。如果你在现实生活中像这样破坏数据,其他开发人员会追捕你并将你烧死在火刑柱上(当然,比喻地说......)。
关于java - 如何将数组作为节点列表返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42823343/