I am currently learning Java and data structures, and I am trying to use insertion to insert the values in a double array to a LinkedList by only inserting each element at the end of the list. I've seen many samples online but the structure I am working with is different from what I've seen which is throwing me off and I tried implementing it in the same way. I have three Java files in the same folder: 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.
}
Currently, the code is stuck in a forever loop because of the while loop in the add_simple method. I'm not sure what I am doing wrong here.
firstNode = newNode
you’re done. Don’t proceed to the loop below in that case. You are creating a data loop.lastNode
such that it always refers to the most recently added entry, so that you don’t have to loop at all.WA7_List
so I was thinking that I had to keep track of thefirst_node
andlast_node
which I assume would be the last element inserted into the linked list. But correct me if im wrong!