简体   繁体   中英

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;
}
if (start == null)
    start = newNode;

You probably want to return after this, since you're done adding the newNode .

if (ptr == start)
    start = newNode;

This will cause the old value of start to be lost. Presumably you want to connect newNode to start .

else 
    insert = newNode;

This doesn't do anything, since insert isn't used anywhere else.

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;
    }

}

I tried to change as little as possible:

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

    // the former if is not necessary, will be handled by if at the end

    while (ptr != null && newEntry >= ptr.data){
        insert = ptr; // the node which will point to the new entry
        ptr = ptr.next;
    }

    Node newNode = new Node(newEntry, ptr); // don't forget the rest of the list!

    if (insert == null)
        start = newNode; // first node of empty list or ordered first
    else
        insert.next = newNode; // insertion point found to insert node after
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM