javadata-structureslinked-listsingly-linked-list

Java: Inserting node at the end of a LinkedList


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.


Solution

  • Try this. Read comments for explanation.

    public void add_simple(double item) {
        LinkedNode newNode = new LinkedNode(null, item);
        if (first_node == null) {
            first_node = newNode;// init first element
            last_node = newNode;// if first_node==null, the last_node is null too
            count_nodes += 1;
            return; //do nothing else if first element
        }
        last_node.next = newNode;// link new element to last element in list
        last_node = newNode; // item now is the last element
        count_nodes += 1;
    }