问题描述
我正在为我的数据结构类处理一个项目,该项目要求我编写一个类来实现INT的链表。使用Node的内部类。包括下面的方法。编写一个测试程序,使您能够以任何顺序使用您想要的任何数据来测试所有方法。我必须创建三个不同的构造函数。其中一个构造函数是一个构造函数,它接受一个整型数组,并创建一个包含所有整型的链表。我试着做了下面的代码。但我不确定我写的代码是否正确?是否有人可以验证我是否正确编写了代码,或者是否可以让我知道需要更改哪些内容才能正确编写代码?
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。
执行转换的一种方法是将数组的每个元素转换为Node,在执行过程中链接到前一个元素,如下所示。
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 - 1].nextNode = nodes[index]; } } head = nodes[0]; }
这里,nodes只是一个局部变量,因为在构造函数完成后您不再需要它。