我是否正确地编写了这个构造函数?
原学程将引见我能否准确天编辑了这个结构函数?的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。
成绩描写
我正在为我的数据构造类处置1个项目,该项目请求我编辑1个类去完成INT的链表。应用Node的外部类。包含上面的办法。编辑1个尝试法式,使您可以或许以所有次序应用您想要的所有数据去尝试一切办法。我必需创立3个分歧的结构函数。个中1个结构函数是1个结构函数,它接收1个整型数组,并创立1个包括一切整型的链表。我试着做了上面的代码。但是我没有肯定我写的代码能否准确?能否有人不妨验证我能否准确编辑了代码,或许能否不妨让我晓得须要变动哪些实质能力准确编辑代码?
import java.util.Random;
public class LinkedListOfIntsTest {
Node head;
int[] array;
Node other;
private class Node {
int value;
Node nextNode;
public Node(int value, Node nextNode) {
this.value = value;
this.nextNode = nextNode;
}
}
public LinkedListOfIntsTest() {
}
public LinkedListOfIntsTest(int[] other) {
array = new int[other.length];
}
推举谜底
可,全部设法主意是将数组转换为LinkedList
,而不只仅是保存数组。是以,您应当从类的字段中增除Node other
以及int[] array
。
履行转换的1种办法是将数组的每一个元素转换为Node
,在履行进程中链交到前1个元素,以下所示。
public LinkedListOfIntsTest(int[] other) {
Node[] nodes = new Node[other.length];
for( int index = 0; index < other.length; index++ ) {
nodes[index] = new Node(other[index], null);
if (index > 0) {
nodes[index - 一].nextNode = nodes[index];
}
}
head = nodes[0];
}
这里,nodes
只是1个部分变质,由于在结构函数完成后您没有再须要它。
佳了闭于我能否准确天编辑了这个结构函数?的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。