Search code examples
javalinked-listsingly-linked-list

adding elements to a singly linked list


I am writing a method for a singly linked list of integers that will sort them as they are entered. something isn't going right because my lists are all empty, or they have random entries in them.

public void add(int newEntry){
    Node ptr = start;
    Node insert = null;

    Node newNode = new Node(newEntry, null);

    if (start == null)
        start = newNode;

    while (ptr != null && newEntry >= ptr.data){
        ptr = ptr.next;
    }

    if (ptr == start)
        start = newNode;
    else 
        insert = newNode;
}

Solution

  • You're not considering all the required edge cases. For this method to work, try something like this:

    public void add(int newEntry){
    
        Node newNode = new Node(newEntry, null);
    
        if (start == null) {
            start = newNode;
        }
    
        else if (newEntry <= start.data) {
            newNode.next = start;
            start = newNode;
        }
    
        else {
            Node ptr = start;
            Node prv = null; // save a reference to previous node
            while (ptr != null && newEntry > ptr.data) {
                prv = ptr;
                ptr = ptr.next;
            }
            prv.next = newNode;
            newNode.next = ptr;
        }
    
    }