我目前正在学习Java和数据结构,我正在尝试使用插入将双精度数组中的值插入到LinkedList中,只需在列表末尾插入每个元素。我在网上看到了很多示例,但我正在使用的结构与我所看到的不同,这让我感到困惑,我尝试以相同的方式实现它。我在同一文件夹中有三个 Java 文件:
Project.java
、LinkedNode.java
、WA7_List.java
。
Project.java
public class Project{
public static void main(String[], args) {
double[] all_inserts = [0.76697, 0.08368, 0.37785, 0.07386, 0.77287]
}
WA7_List linked_list = new WA7_List(M); // M is an int variable used later but can be ignored for this post.
for (int i=0; i<all_inserts.length; i++)
{
linked_list.add_simple(all_inserts[i]);
}
}
LinkedNode.java
public class LinkedNode {
public LinkedNode next;
public double item;
public LinkedNode(LinkedNode next, double item) {
this.next = next;
this.item = item;
}
}
WA7_List
public class WA7_List {
private LinkedNode first_node;
private LinkedNode last_node;
private LinkedNode[] shortcuts;
private int count_shortcuts;
private int count_nodes;
private int M;
public WA7_List(int M) {
this.first_node = null;
this.last_node = null;
this.shortcuts = null;
this.count_nodes = 0;
this.count_shortcuts = 0;
this.M = M;
}
public void add_simple(double item) {
LinkedNode newNode = new LinkedNode(null, item);
if (first_node==null)
{
first_node=newNode;
count_nodes+=1;
}
last_node = first_node;
while (null != last_node.next)
{
last_node = last_node.next;
}
last_node.next = newNode;
}
// There are more methods after but just focused on this first method.
}
目前,由于 add_simple 方法中的 while 循环,代码陷入了永远循环。我不确定我在这里做错了什么。
尝试
public void add_simple(double item) {
LinkedNode newNode = new LinkedNode(null, item);
if (first_node == null) { // the list is empty
first_node = newNode; // we set the first node
} else {
last_node.next = newNode; // the new is the next of the last node
}
last_node = newNode; //always: the new is the last
}